Recall & Review
beginner
What is a counter-based while loop?
A counter-based while loop repeats a block of code while a counter variable meets a condition, usually increasing or decreasing the counter each time to eventually stop the loop.
Click to reveal answer
beginner
Why do we need a counter variable in a while loop?
The counter variable helps control how many times the loop runs. It changes each time the loop runs so the loop can stop when the counter reaches a limit.
Click to reveal answer
beginner
What happens if the counter is not updated inside a while loop?
If the counter is not updated, the loop condition may never become false, causing an infinite loop that runs forever.
Click to reveal answer
beginner
Example: What does this code print?
int i = 1;
while (i <= 3) {
System.out.println(i);
i++;
}
It prints:
1
2
3
The loop starts with i=1 and prints i, then increases i by 1 each time until i is greater than 3.
Click to reveal answer
beginner
How to avoid infinite loops in counter-based while loops?
Always update the counter inside the loop so the condition will eventually become false. Also, check the loop condition carefully before running the loop.
Click to reveal answer
What is the role of the counter in a counter-based while loop?
✗ Incorrect
The counter controls the number of loop repetitions by changing each time the loop runs.
What happens if you forget to increase the counter inside a while loop?
✗ Incorrect
Without increasing the counter, the loop condition never becomes false, causing an infinite loop.
Which of these is a correct way to start a counter for a while loop that runs 5 times?
✗ Incorrect
All these ways correctly use a counter to run the loop 5 times.
What will this code print?
int i = 3;
while (i > 0) {
System.out.println(i);
i--;
}
✗ Incorrect
The loop prints 3, then 2, then 1, decreasing i each time until i is 0.
Which part of a counter-based while loop changes each time the loop runs?
✗ Incorrect
The counter variable is updated each time to eventually stop the loop.
Explain how a counter-based while loop works and why the counter must be updated inside the loop.
Think about how the loop knows when to stop.
You got /4 concepts.
Write a simple Java while loop that prints numbers from 1 to 5 using a counter.
Start with int i = 1; and use i <= 5 as condition.
You got /4 concepts.