Member Avatar for Codeslinger

/*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);
	}
   }
}

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 .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.