/*THE OUTPUT SHOULD BE LIKE THIS:

2 4 6 8 10 - 30 //gets the sum of first column
12 14 16 18 20 - 60 //gets the sum of second column
1 2 3 4 5 - 15 //gets the sum of third column
6 5 4 3 2 - 20 //gets the sum of fourth column
125 //gets the sum of all columns
*/

//HERE IS MY CODE:

``````public class test
{
public static void main(String[] ar) {
int[][] num = {{2, 4, 6, 8, 10},
{12, 14, 16, 18, 20},
{1, 2, 3, 4, 5},
{6, 5, 4, 3, 2}};
int sum = 0;

for(int i=0; i<4; i++)
{
for(int j=0; j<5+1; j++)
{
System.out.print(" " + num[i][j]);
sum += num[0][j];
}

System.out.println(" " + sum);
}
}
}``````

Edited by Codeslinger: SPACING

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by apines

First, [TEX]12+14+16+18+20\neq 60[/TEX], it's 80 :). Second, every time you finish the inner loop you need to init sum to zero again, otherwise it will sum up the entire matrix and not just the rows.

i don't know also the idea behind making j < 5+1 it's ok with j < 5 , also
sum += num[0][j]; it must be sum += num[j]; not 0 , and as apines mentioned the sum variable must be declared inside the first loop

yeah Abed_eid you're right, didn't notice that - when iterating over arrays, especially two dimensional arrays with uneven rows, it is better to use `arrayName.length` and `arrayName[index].length` .

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.