09 June, 2013

C++ Program To Find & Print Sum Of Diagonal Elements Of Matrix.

This Post Contains A C++ Program To Find & Print Sum Of Diagonal Elements Of Matrix With Correct Source Code, Algorithm & Output. This Program Is Written, Compiled & Executed At TurboC/C++3.0 Compiler & Will Help You To Understand The Concept Of 'Arrays', 'Nested Loops' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.

# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.



C++ Program To Find & Print Sum Of Diagonal Elements Of Matrix.

/* Declaration Of Header Files */
#  include  <iostream.h>
#  include  <conio.h>

/* Start Of Main Program */
void main()
{
   
       /* Declaration Of Variables */
       int  i,  j,  r  =  0,  c  =  0;
       int  a [ 10 ][ 10 ];
       clrscr();

       /* Asking For The Input From User */
       cout  <<  "  Enter Number Of Rows & Columns Of 2D Array [ Matrix ]  :  ";
       cin  >>  r  >>  c ;
      
       //  Accepting Values Of 2D Array [ Matrix ]
       cout  <<  "  Enter  "  <<  r  *  c  <<  "  Values for 2D Array  :  ";
       for  (  i  =  0;  i  <  r;  i++  )
       {
                for  (  j  =  0;  j  <  c;  j++  )
                {
                         cin  >>  a [ i ][ j ];
                }
       }

       // Printing Values Of 2D Array [ Matrix ]
       cout  <<  "  Values Of 2D Array [ Matrix ] Are  :  ";
       for  (  i  =  0;  i  <  r;  i++  )
       {
                cout  <<  " \n ";
                for  (  j  =  0;  j  <  c;  j++  )
                {
                         cout  <<  a [ i ][ j ];
                }
       }
/* Source Code For Computing Sum Of Diagonal Elements If & Only If Rows & Columns Are Equal */
sum=0;
if(r==c)
{
   for(i=0; i<r; i++)
   {
      for(j=0; j<c; j++)
      {
         if(i+j==0 || i+j==2 || i+j==4)
         {
            sum=sum+a[i][j];
         }
      }
   }
   /* Printing The Output Onto The Screen/Console */
   cout<<"\n Sum Of Diagonal Elements Of Array Is : "<<sum;
}
else
{
   cout<<" \n Addition Is Not Possible";
}
getch();
}
/* End Of Main Program */ 


Output :

Enter Order For Array A : 3 3

Enter 9 Values For Array :
1  2  3  4  5  6  7  8  9

Array A Is :
1  2  3
4  5  6
7  8  9

Sum Of Diagonal Elements Of Array Is : 15






No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.

Blog Archive