Chris Valenzuela
Chris Valenzuela

Reputation: 39

having trouble SUM PER ROW

Im having trouble on my code, I want to print it ROW by Row but I ended up adding all those numbers-

Should look like this --> sum of row 0 is "" sum of row 1 is "" sum of row 2 is ""

public class NewClass
{
          public static void main( String[] arg )
          {
           int[][] data = 
            { { 1, 2},
              { 2, 2},
              { 1, 2, 4, 5},
              { 2, 2, 4,},
              { 1, 1, 4, 5 },
              { 2, 1}};

               int sum = 0;

               for ( int row=0; row < data.length; row++)
                 for ( int col=0; col < data[row].length; col++)
                   sum = sum + data[row][col];

                System.out.println( sum );
              }
}

Upvotes: 0

Views: 77

Answers (3)

vels4j
vels4j

Reputation: 11298

Have two variables and accumulate it.

int totalSum = 0;
for (int row = 0; row < data.length; row++) {
    int rowSum = 0;
    for (int col = 0; col < data[row].length; col++) {
        rowSum = rowSum + data[row][col];
    }
    System.out.println("Sum of " + (row + 1) + " is " + rowSum);
    totalSum += rowSum;
}
System.out.println("TotalSum " + totalSum);

Upvotes: 0

kosa
kosa

Reputation: 66637

Move sum inside first loop as well as print also.

 for ( int row=0; row < data.length; row++)
        {
           int sum = 0;
          for ( int col=0; col < data[row].length; col++)
          {
           sum = sum + data[row][col];
          }
          System.out.println( sum );
        }

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 837946

You want the outer loop to include the initialization of the sum variable and the printing:

for ( int row=0; row < data.length; row++) {
     int sum = 0;
     for ( int col=0; col < data[row].length; col++) {
          sum += data[row][col];
     }
     System.out.println("sum of row " + row + " is " + sum);
}

Upvotes: 3

Related Questions