# Thread: 2D Array - Sum of columns

1. Member
Join Date
Feb 2011
Posts
8
Rep Power
0

## 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.
Java 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]);
}```

2. Change one line to the following and you're in business:

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

Jos

3. Member
Join Date
Feb 2011
Posts
8
Rep Power
0
Originally Posted by JosAH
Change one line to the following and you're in business:

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

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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•