#### C++ Program To Create A 3 × 3 Matrix And Calculate The Sum Of The Numbers In Each Row, Each Column, Left Diagonal And Right Diagonal

by

, 09-04-2012 at 11:49 AM (144714 Views)
Problem Description

a) Using a C++ program, create a 3 × 3 matrix and store the natural numbers in it rowwise.

e.g.,

1 2 3 4 5 6 7 8 9

Now write a program to print the following output:

i) Sum of the numbers in each row.

ii) Sum of the numbers in each column.

iii) Sum of the numbers in left diagonal.

iv) Sum of the numbers in right diagonal.

b) Differentiate between subscript and subscript variable.

Solution:

The first nine natural numbers are to be generated using a loop and the values are to be stored in a double dimensional array.

Using 4 different loops the various sums are to be calculated.

For calculating the row and column totals, the procedure is simple, each row and column are totaled and the sum displayed.

For calculating the left diagonal - if the row and column subscripts of an element are equal, then those elements are summed.

For calculating the right diagonal - if the row and column subscripts of an element add up to 2, they are summed.

Code:#include<iostream.h> void main() { int a[3][3], x, y, z, s; z=1; for(x=0; x<3; x++) for(y=0; y<3; y++) {a[x][y]=z; z++;} //The array is now full. //Finding sum of each row cout<<"\n The sum of each row="; for(x=0; x<3; x++) s=0; for(y=0; y<3; y++) s=s+a[x][y]; cout<<s<<" "; } //The sum of each column can now be calculated cout<<"\n The sum of each column=>"; for(y=0; y<3; y++) { s=0; for(x=0; x<3; x++) s=s+a[x][y]; cout<<s<<" "; } //The sum of the left diagonal is now calculated cout<<"\n The sum of the left diagonal="; s=0; for(x=0; x<3; x++) { for(y=0; y<3; y++) if(x==y)s=s+a[x] [y]; cout<<s; //Sum of the right diagonal cout<<"\n The sum of the right diagonal="; s=0; for(x=0; x<3; x++) { for(y=0; y<3; y++) if(x+y=2) s=s+a[x][y]; } cout<<s; } //end of main function