AP Computer Science A · Topic 4.1
while Loops Practice
Part of Iteration.
Practice questions
30
Sample questions
5 of 30 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
int i = 10; while (i < 5) { System.out.println(i); i++; } System.out.println("done");What is printed?
- Acheck_circle
done
- B
10 done
- C
nothing
- D
10 11 12 done
Why
The while condition (10 < 5) is false at the start, so the loop body never executes. Only "done" prints.
- A
Sample 2difficulty 2/5
What is printed?
<code>int i = 0; while (i < 3) { System.out.print(i + " "); i++; } </code></pre>
- A
1 2 3
- B
Infinite loop
- C
0 1 2 3
- Dcheck_circle
0 1 2
Why
Loops while i < 3: prints 0, 1, 2.
- A
Sample 3difficulty 2/5
int n = 1; while (n < 16) { n *= 2; } System.out.println(n);What is printed?
- Acheck_circle
16
- B
8
- C
32
- D
15
Why
n doubles each time: 1, 2, 4, 8, 16. When n becomes 16 the condition n < 16 is false and the loop exits. n is 16.
- A
Sample 4difficulty 3/5
do { System.out.println(i); i++; } while (i < 0);Which loop is equivalent in behavior when i starts at 5?
- A
An infinite loop
- B
No iterations occur
- Ccheck_circle
System.out.println(5); i = 6; (loop runs exactly once)
- D
Loop runs five times
Why
A do-while runs at least once and only repeats while the condition is true. Starting at 5 the body runs once, prints 5, increments to 6, and 6 < 0 is false.
- A
Sample 5difficulty 3/5
int product = 1; for (int i = 1; i <= 5; i++) { if (i == 3) continue; product *= i; } System.out.println(product);What is printed?
- Acheck_circle
40
- B
120
- C
60
- D
24
Why
Skip i=3. Product = 1<em>1</em>2<em>4</em>5 = 40.
- A