AP Computer Science A · Topic 4.5
Informal Code Analysis (Loop Tracing) Practice
Part of Iteration.
Practice questions
10
Sample questions
5 of 10 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
int sum = 0; for (int i = 1; i < 5; i++) { sum += i; } System.out.println(sum);What is printed?
- Acheck_circle
10
- B
5
- C
14
- D
15
Why
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.
- A
Sample 2difficulty 3/5
How many iterations does <code>for (int i = 0; i <= 10; i++)</code> perform?
- A
10
- B
9
- Ccheck_circle
11
- D
12
Why
i = 0, 1, 2, ..., 10 → 11 values.
- A
Sample 3difficulty 3/5
How many times does <code>for (int i = 5; i < 100; i += 5)</code> execute?
- A
21
- B
18
- C
20
- Dcheck_circle
19
Why
i: 5, 10, 15, ..., 95 → 19 values.
- A
Sample 4difficulty 4/5
String result = ""; for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) { result += "*"; } result += "|"; } System.out.println(result);What is printed?
- A
<strong>|</strong><em>|</em>***|
- B
<em><strong>|</strong>|</em>|
- C
<em>|</em>|*|
- Dcheck_circle
<em>|<strong>|</strong></em>|
Why
For i=1: one "<em>", then "|". For i=2: two "</em>", then "|". For i=3: three "<em>", then "|". Result: "</em>|<strong>|</strong>*|".
- A
Sample 5difficulty 4/5
<code>for (int i = 0; i <= arr.length; i++)</code> (note <code><=</code>) on a length-5 array
- A
Compile error
- B
Works fine
- C
Skips one element
- Dcheck_circle
Throws ArrayIndexOutOfBoundsException at i=5
Why
Valid indices are 0..length-1; <code><=</code> would access index <code>length</code> (out of bounds).
- A