Nested Iteration

AP Computer Science A· difficulty 5/5

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

What is printed?

  • A

    30

  • B

    40

  • C

    35

    check_circle
  • D

    60

Explanation

i=1 inner skipped. i=2: j=1 -> 2*1=2. i=3: j=1,2 -> 3+6=9. i=4: j=1,2,3 -> 4+8+12=24. Total = 2+9+24 = 35.

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

Related questions