How to get the sum of rows and columns in 2 dimensional array?

Here's my code for adding the rows and columns. My problem is that my program displays an incorrect output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
main()
{
	int a[20][20],r,c,y,x,sum=0,rn,cn,cs=0,rs=0;
	
	cout<<"Enter number of columns : ";
	cin>>cn;
	
	cout<<"Enter number of rows : ";
	cin>>rn;
	
	cout<<"Enter "<<rn*cn<<" numbers : "<<endl;	
	
	for(r=0; r<rn; r++)
	 {
	   for(c=0; c<cn; c++)
	    {
	      cout<<">";
	 	  cin>>a[r][c];
	    }
     }
     
    cout<<"The numbers are"<<endl; 
    for(r=0; r<rn; r++)
	 {
	 	cout<<endl;
	   for(c=0; c<cn; c++)
	    {
	      cout<<a[r][c]<<"\t";
        }
     }
     
    for(r=0; r<rn; r++)//my code for getting the sum of 2d array
     {
       for(c=0; c<cn; c++)
        {
          cs=cs+a[r][c];
        }
       cout<<cs<<" ";//but the output is incorrect
     }
} 


This should be the output
Enter number of columns: 4
Enter number of rows: 3
Enter twelve numbers: 9 2 3 4 2 3 1 2 5 6 7 8
The numbers are:
9	2	3	4
2	3	1	2
5	6	7	8
Sum of number 1 column is: 16
Sum of number 2 column is: 11
Sum of number 3 column is: 11
Sum of number 4 column is: 14
Sum of number 1 row is: 18 
Sum of number 2 row is: 8
Sum of number 3 row is: 26


Last edited on
You've provided the expected output, which is a good start, but you haven't provided a compilable code snippet or told us how the actual output differs from what is expected.
I just want to display the sum of rows and columns of 2d array
Lets use your example data. rn==3. Lets unroll the outer loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int cs=0;

for ( c=0; c < cn; c++ ) {
  cs = cs + a[0][c];
}
cout << cs << " "; // prints 18

for ( c=0; c < cn; c++ ) {
  cs = cs + a[1][c];
}
cout << cs << " "; // prints 26

for ( c=0; c < cn; c++ ) {
  cs = cs + a[2][c];
}
cout << cs << " "; // prints 52 

Can you yourself now see what goes wrong?
26 and 52 is an incorrect input it should be 18, 8 and 26

how can I correct that... please help me
Last edited on
Disregard what I said, I was obviously wrong.
Last edited on
@judo11


What keskiverto is trying to tell you, is you must reset the variable 'cs', back to a '0' AFTER using the cout to display its value at the time, otherwise, all you're doing is getting the total value for ALL the rows, not individual rows.
Topic archived. No new replies allowed.