AP Computer Science A · Topic 4.4
Nested Iteration Practice
Part of Iteration.
Practice questions
18
Sample questions
5 of 18 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 3/5
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) { System.out.println("x"); } }What is wrong?
- A
Compile-time inference fails
- B
Nothing is wrong
- C
Both loops share i and run nine times correctly
- Dcheck_circle
Inner loop redeclares i; that variable is already in the enclosing scope
Why
Java disallows declaring a variable with the same name as one already in an enclosing block. Rename the inner variable, e.g., j.
- A
Sample 2difficulty 3/5
int sum = 0; for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { sum += j; } } System.out.println(sum);What is printed?
- Acheck_circle
18
- B
6
- C
9
- D
27
Why
Inner loop sums 1+2+3 = 6. Outer loop runs 3 times, so total = 6 * 3 = 18.
- A
Sample 3difficulty 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
- Dcheck_circle
14
Why
i=1: j=1,2,3 -> 6. i=2: j=2,3 -> 5. i=3: j=3 -> 3. Total = 6 + 5 + 3 = 14.
- A
Sample 4difficulty 3/5
int count = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { count++; } } System.out.println(count);What is printed?
- A
7
- Bcheck_circle
12
- C
16
- D
9
Why
Outer loop runs 3 times, inner loop runs 4 times each. Total iterations = 3 * 4 = 12.
- A
Sample 5difficulty 3/5
public static int run() { int s = 0; for (int i = 0; i < 5; i++) { if (i == 3) continue; s += i; } return s; } // Call: System.out.println(run());What is printed?
- Acheck_circle
7
- B
8
- C
10
- D
6
Why
Sum 0+1+2+4 = 7 (skipping 3).
- A