# 2D Array - Sum of columns

• 02-28-2011, 08:04 PM
dutchgold92
2D Array - Sum of columns
I'm doing a class exercise featuring an array of arrays, requiring me to calculate the sum of all array elements, the sum of each row, and the sum of each column. The latter I can't understand how to do.

Here's the program - some parts are temporary, just included to ease the editing for me.
Code:

```        public static void main(String[] args)         {                 final int array[][] = new int[6][4];                 int total = 0;                 int rowTotal[] = new int[6];                 int columnTotal[] = new int[4];                 for (int i = 0; i < array.length; i++)                         for (int x = 0; x < 4; x++)                         {                                 array[i][x] = (int)(Math.random() * 10000) % 10 + 1;                                 System.out.println(i + "\t" + x + "\t" + array[i][x]);                                 total = total + array[i][x];                                 rowTotal[i] = rowTotal[i] + array[i][x];                                 columnTotal[x] = columnTotal[x] + array[x][x];                         }                 System.out.println("Total: " + total);                 System.out.println("Total for row one: " + rowTotal[0]);                 System.out.println("Total for column one: " + columnTotal[0]);         }```
• 02-28-2011, 08:10 PM
JosAH
Change one line to the following and you're in business:

Code:

`columnTotal[x] = columnTotal[x] + array[i][x];`
kind regards,

Jos
• 02-28-2011, 08:18 PM
dutchgold92
Quote:

Originally Posted by JosAH
Change one line to the following and you're in business:

Code:

`columnTotal[x] = columnTotal[x] + array[i][x];`
kind regards,

Jos

No idea how I didnt get that. :o Cheers.