user3286008
user3286008

Reputation: 13

Summing up each row and column in Java

/*
 * Programmer: Olawale Onafowokan
 * Date: February 6, 2014
 * Purpose: Prints the row and column averages
 */
class Lab4 {
    public static void main(String[] args) {
        int [][] scores = {{ 20, 18, 23, 20, 16 },
            { 30, 20, 18, 21, 20 },
            { 16, 19, 16, 53, 24 },
            { 25, 24, 22, 24, 25 }};
        outputArray(scores);
    }

    public static void outputArray(int[][] array) {
        int sum= 0;
        int rowSize = array.length;
        int columnSize = array[0].length;
        System.out.println("rows=" + rowSize + "cols=" + columnSize);

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                sum += array[i][j];
            }
            System.out.println("Print the sum of rows = " + sum);
        }
        for (int i = 0; i < array.length; i++) {
            sum = 0;
            sum = sum + array[i][j];
            // It is telling me the j can't be resolved
        }
    }
}

The program prints out:

rows=4cols=5
Print the sum of rows = 612
Print the sum of rows = 20358
Print the sum of rows = 652058
Print the sum of rows = 20866609

I don’t understand why it isn't adding up the numbers correctly. I am trying to add up each row and column. I am not even sure where these numbers are coming from.

Upvotes: 1

Views: 53979

Answers (7)

Ram Pukar
Ram Pukar

Reputation: 1621

public class Main {
    public static void main(String[] args) {
        ArrSort objArr = new ArrSort();
        int[][] arr = {
            {1,2,3},
            {4,5,6},
            {1,2,3}
        };

        objArr.getColsSum(arr);

    }
}

class ArrSort {
    public void getColsSum(int[][] arg){
        int[] colsSum = new int[3];
        colsSum[0] = 0;
        colsSum[1] = 0;
        colsSum[2] = 0;

        for(int i = 0; i<arg.length; i++) {
            for(int j = 0; j<arg[i].length; j++) {
                System.out.print(arg[i][j] +" ");
                if(j==0) {
                    colsSum[j]+=arg[i][j];
                } else if(j==1) {
                    colsSum[j]+= arg[i][j];
                } else {
                    colsSum[j]+= arg[i][j];
                }
            }
            System.out.println();
        }
        for(int i = 0; i<colsSum.length; i++){
            System.out.print(colsSum[i] + " ");
        }
    } 
}

DEMO enter image description here

Upvotes: 1

Geo
Geo

Reputation: 1

this for loop of yours is out of scope btw. check with the compiler:

output : when taking out sum = sum + array[i][j]

rows=4cols=5
Print the sum of rows = 97
Print the sum of rows = 206
Print the sum of rows = 334
Print the sum of rows = 454

after that it would work but it gives sum of all rows not breaking them.

for (int i = 0; i < array.length; i++) {
        sum = 0;
        sum = sum + array[i][j];
        // It is telling me the j can't be resolved
    }
//j is out of scope there is no such thing as j in this loop

English: pseudo code

adding one set of row then stop. r1
r2
r3
r4
or arrays if you want r[x]

each time cleaning the sum instead of adding them to each other.
so you need 4 sums of rows

and 5 sums of columns
c1
c2
c3
c4
c5

so you do a loop for horizontal summation and one vertical summation.

also don't put your name on top of the assignment.

output after fix
rows=4cols=5
Print the sum of rows = 97
Print the sum of rows = 109
Print the sum of rows = 128
Print the sum of rows = 120
BUILD SUCCESSFUL (total time: 0 seconds)

now you need to do this for columns 5 times

Upvotes: 0

Geo
Geo

Reputation: 1

"you don't have to use the operator "+=", simply use "="."

... actually he needs the += but then he is using it wrong.

logically speaking his code is wrong.

it should be += then after each instance of the outer for loop he should be cutting it off by resetting the sum of the value to 0 again to give out new values.

Upvotes: 0

Baby
Baby

Reputation: 5092

Here is your problem:

sum += sum + array[i][j];

sum += sum + array[i][j] is the same as sum = sum + sum + array[i][j] (you added sum twice)

Should be:

sum = sum + array[i][j]; Or sum += array[i][j];

If you want to print the sum of each row only, reset your sum to 0 for each iteration on outer for-loop

for (int i = 0; i < array.length; i++){
    sum=0;
    ....  

If you want to print the sum of each column only, you need to add this:

int[] colSum =new int[array[0].length];  

Then inside for-loop , add

colSum[j]+=array[i][j]; 

So finally you will have this:

int[] colSum =new int[array[0].length];
for (int i = 0; i < array.length; i++){   
    for (int j = 0; j < array[i].length; j++){                
        sum += array[i][j];
        colSum[j] += array[i][j];
    }
    System.out.println("Print the sum of rows =" + sum);
}  
for(int k=0;k<colSum.length;k++){
    System.out.println("Print the sum of columns =" + colSum[k]);
} 

Upvotes: 4

roy5150
roy5150

Reputation: 1

You don't have to use the operator "+=", simply use "=".

Upvotes: 0

AAB
AAB

Reputation: 1653

 for (int i = 0; i < array.length; i++)
    {   
      sum=0;
      for (int j = 0; j < array[0].length; j++)
      {                
        sum += array[i][j]; 

      }

     System.out.println("Print the sum of rows =" + sum);
    }  

try intializing sum =0;

For Sum of Columns you could do this

class Sample{
    public static void main(String []args){
        int arr[][]={{1,2,3},{1,2,3},{1,2,3}};
        int sum=0;
        for(int col=0;col<arr[0].length;col++){
            for(int row=0;row<arr.length;row++){
                sum+=arr[row][col];
            }
            System.out.println("Sum is "+sum);
            sum=0;
        }
    }
}

Upvotes: 0

arcy
arcy

Reputation: 13103

Your outer loop (controlled with i) executes once for each row. If you want to sum all the numbers in one row, set sum to zero at the beginning of each loop.

If you have "sum = sum + x", that will add x to sum and store in sum. If you write "sum += x", that will do the same thing. But you have written "sum += sum + x", which adds in sum AND x to sum.

Upvotes: 0

Related Questions