Informal Code Analysis (Loop Tracing)

AP Computer Science A· difficulty 2/5

int sum = 0;
for (int i = 1; i < 5; i++) {
  sum += i;
}
System.out.println(sum);

What is printed?

  • A

    10

    check_circle
  • B

    5

  • C

    14

  • D

    15

Explanation

The condition is i < 5, so i takes values 1, 2, 3, 4 (NOT 5). Sum = 1+2+3+4 = 10. A common off-by-one bug if the author wanted 1..5.

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

Related questions