AP Computer Science A · Topic 4.2
for Loops Practice
Part of Iteration.
Practice questions
32
Sample questions
5 of 32 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
int count = 0; for (int i = 1; i <= 20; i++) { if (i % 2 == 1) { count++; } } System.out.println(count);What is printed?
- Acheck_circle
10
- B
11
- C
20
- D
9
Why
Odd numbers from 1 to 20 are 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 — exactly 10 numbers.
- A
Sample 2difficulty 2/5
int i = 5; while (i > 0) { System.out.print(i); i--; }What is printed?
- A
12345
- Bcheck_circle
54321
- C
5432
- D
01234
Why
The while prints i then decrements, while i > 0: prints 5, 4, 3, 2, 1. After i becomes 0, condition is false. Output is "54321".
- A
Sample 3difficulty 2/5
int sum = 0; for (int i = 1; i <= 5; i++) { sum += i; } System.out.println(sum);What is printed?
- Acheck_circle
15
- B
10
- C
14
- D
21
Why
The loop adds 1+2+3+4+5 = 15 to sum.
- A
Sample 4difficulty 2/5
public static void printReverse(int[] a) { for (int i = /* missing */; i >= 0; i--) { System.out.println(a[i]); } }Which expression replaces /* missing */?
- Acheck_circle
a.length - 1
- B
a.length + 1
- C
a.length
- D
0
Why
The last valid index is a.length - 1. Iterate downward from there to 0.
- A
Sample 5difficulty 2/5
int sum = 0; for (int i = 0; i <= 10; i += 2) { sum += i; } System.out.println(sum);What is printed?
- Acheck_circle
30
- B
25
- C
20
- D
55
Why
i takes values 0, 2, 4, 6, 8, 10. Sum = 0+2+4+6+8+10 = 30.
- A