Saturday, 8 September 2012

Sum of Row & Column In 2D Matrix

Heres the code by which you could be adding the rows and columns of a 2D Matrix











#include<iostream.h>
#include<conio.h>
void main()
{   clrscr();
int a[3][3];
int i,j,s=0,sum=0;

cout<<"Enter 9 elements of 3*3 Matrix \n";
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>a[i][j];

cout<<"Matrix Entered By you is \n";
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
  cout<<a[i][j]<<" ";
   cout<<endl;
}

for(i=0;i<3;i++)
{for(j=0;j<3;j++)
  s=s+a[i][j];
 cout<<"sum of"<<i+1<<" Row is"<<s;
  s=0;
  cout<<endl;
}
 cout<<endl;
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
  s=s+a[j][i];
 cout<<"sum of"<<i+1<<" Column is"<<s;
  s=0;
  cout<<endl;
}

 cout<<endl;

for(i=0;i<3;i++)
sum=sum+a[i][i];
 cout<<"Sum of Diagnols Elements is \n"<<sum;

getch();
}


9 comments:

  1. Thanks this is really useful! Thanks once again

    ReplyDelete
  2. brother, one small mistake

    in column row, the loop should be

    for(j=0;j<3;j++)
    {for(i=0;i<3;i++)
    {s=s+a[i][j];
    cout<<i+1<<"row sum is: ";
    }

    ReplyDelete
  3. Awesome! However, I used the code and got garbage on the very first row, but what fixed it was "s=0;" placed after the first for loop.
    for(i=0;i<3;i++){
    s=0;
    for(j=0;j<3;j++){
    s=s+a[i][j];
    cout<<"sum of"<<i+1<<" Row is"<<s;

    cout<<endl;
    }
    }

    ReplyDelete
  4. thanks very easy and understandable code

    ReplyDelete
  5. Why do we write i +1 in the cout statment?
    And why should we write s=0?

    ReplyDelete