5
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've written so far. The problem I encounter is that i is 0 at the first iteration making i%6=0 as well and making it so that row 1 consists of arr[0][0] only and each next row ends with the actual first of the next one.

I have a feeling the solution must be easy but I haven't found one for the past hour or so. Any help would be appreciated.

1
  • The task is about not using an inner loop. I must find the sum of each row using one loop. Commented Jun 5, 2016 at 12:07

2 Answers 2

4

Instead of comparing i%6 to zero, compare it to 5, the last number before the remainder drops to zero again. This would let you do the output when you reach the last element of the current row, rather than waiting to reach the initial element of the next row (and dropping the printout for the last row altogether).

if (i % 6 == 5) {
    System.out.println();
    System.out.println("Sum of row " + (rowIndex + 1) + " is: " + sum);
    rowsSum += sum;
    sum = 0;
    rowIndex++;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.