Nested Iteration

AP Computer Science A· difficulty 3/5

public static int run() {
    int s = 0;
    for (int i = 1; i <= 3; i++) {
        for (int j = i; j <= 3; j++) {
            s += j;
        }
    }
    return s;
}
// Call: System.out.println(run());

What is printed?

  • A

    18

  • B

    12

  • C

    9

  • D

    14

    check_circle

Explanation

i=1: j=1,2,3 -> 6. i=2: j=2,3 -> 5. i=3: j=3 -> 3. Total = 6 + 5 + 3 = 14.

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

Related questions