Nested Iteration

AP Computer Science A· difficulty 4/5

public static int run() {
    int x = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if (j > i) x += 1;
            else if (j < i) x -= 1;
        }
    }
    return x;
}
// Call: System.out.println(run());

What is printed?

  • A

    0

    check_circle
  • B

    -4

  • C

    8

  • D

    4

Explanation

Above-diagonal count = below-diagonal count for square matrix; net = 0.

Want 10 more like this — adaptive to your weak spots?

Related questions