Finding the sum of rows of a 2D array using 1 loop in java

int[][] arr = { { 11, 12, 13, 14, 15, 16 }, { 21, 22, 23, 24, 25, 26 }, { 31, 32, 33, 34, 35, 36 }, { 41, 42, 43, 44, 45, 46 }, { 51, 52, 53, 54, 55, 56 }, { 61, 62, 63, 64, 65, 66 } }; int sum = 0; int rowsSum = 0; int rowIndex = 0; for (int i = 0; i < arr.length * arr.length; i++) { System.out.print(arr[i / arr.length][i % arr.length] + " "); sum += arr[i / arr.length][i % arr.length]; if (i % 6 == 0) { System.out.println(); System.out.println("Sum of row " + (rowIndex + 1) + " is: " + sum); rowsSum += sum; sum = 0; rowIndex++; } } System.out.println(); System.out.println("Sum of all rows is: " + rowsSum); 

This is what I wrote so far. The problem I am facing is that in the first iteration I equal 0, making i% 6 = 0 and making it so that line 1 only consists of arr [0] [0], and every next line ends the actual first of the next one.

I have a feeling that the solution should be easy, but I have not found it in the last hour or so. Any help would be appreciated.

+5
source share
2 answers

Instead of comparing i%6 with zero, compare it to 5 , the last number before the remaining part will again drop to zero. This will allow you to conclude when you reach the last element of the current line, and not wait until you reach the start element of the next line (and completely discard the printout for the last line).

 if (i % 6 == 5) { System.out.println(); System.out.println("Sum of row " + (rowIndex + 1) + " is: " + sum); rowsSum += sum; sum = 0; rowIndex++; } 
+4
source

OR you can do (i+1) % 6 == 0 instead of i % 6 == 0

 if ((i+1) % 6 == 0) { System.out.println("Sum of row " + (rowIndex + 1) + " is: " + sum); rowsSum += sum; sum = 0; rowIndex++; } 
0
source

All Articles