# Thread: I want to know how to calculate and display the sum of each column in 2D array

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

## I want to know how to calculate and display the sum of each column in 2D array

I want tp create method that calculate and display the sum of each column of a 2D array, for example :

2 6 -1 5
8 2 7 -5
1 0 4 4

The method should display as follow :

The sum of column 0 is 11
The sum of column 1 is 8
The sum of column 2 is 10
The sum of column 3 is 4

I have declared the array in the main program:
Java Code:
```public class Main {
static final int MAXROW;    <-----   MAXROW is a global int constant
static final int MAXCOL;     <-----   MAXCOL is a global int constant

public static void main(String[] args) {

float[][]A = new float[MAXROW][MAXCOL];

}```
and have some method :
Java Code:
```private void calculateColumn(int[][] array, int j)
{
int sum= 0;
for (int row= 0; row < a.length; a++)
sum+= a[row][j];
System.out.println("The sum of column" +j+ "is" + sum);
}

public void calculate(int[][] array) {
for (int col= 0; col < array[0].length; col++)

calculateColumn(array, col);

}```
im stuck in main part because I not very sure whether the method i created is working fine, somomore i not clear how to call the method in the main part
I know the code seesm defect but this is all i got so far,sorry for the limitation of my knowledge...
any suggestion and correction are welcome

2. Senior Member
Join Date
Jan 2011
Location
Bangalore, India
Posts
102
Rep Power
0
Originally Posted by Javanoobs
somomore i not clear how to call the method in the main part
If you don't know how to call a method I'd suggest you learn some basics before you start.

You methods too, are almost wrong.

Java Code:
```for (int row= 0; row < a.length; a++)
sum+= a[row][j];```
Instead of "j" and "a" it should be "row". Think about the logic.
This will calculate the sum of zero-th column. Now you think about a way how to calculate the sum of 1st and 2nd columns.

You need to learn about arrays also before proceeding

#### Posting Permissions

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