Recall & Review
beginner
What is a while loop in C++?
A while loop repeats a block of code as long as a given condition is true. It checks the condition before running the code each time.
Click to reveal answer
beginner
What happens if the condition in a while loop is false at the start?
The code inside the while loop does not run even once if the condition is false at the beginning.
Click to reveal answer
intermediate
How do you stop an infinite while loop?
You stop an infinite while loop by making sure the condition eventually becomes false, usually by changing a variable inside the loop.
Click to reveal answer
beginner
Write a simple while loop that prints numbers from 1 to 5.
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << std::endl;
i++;
}
return 0;
}
Click to reveal answer
beginner
Why is it important to update the variable in the while loop condition?
If you don't update the variable, the condition might never become false, causing the loop to run forever (infinite loop).
Click to reveal answer
What does a while loop do in C++?
✗ Incorrect
A while loop repeats the code block as long as the condition remains true.
What happens if the while loop condition is false at the start?
✗ Incorrect
If the condition is false initially, the while loop code block is skipped.
Which of these can cause an infinite while loop?
✗ Incorrect
If the condition never becomes false and the variable is not updated, the loop runs forever.
How do you usually stop a while loop?
✗ Incorrect
Changing variables inside the loop to make the condition false stops the loop.
What is the output of this code?
int i = 3;
while (i > 0) {
std::cout << i << " ";
i--;
}
✗ Incorrect
The loop prints 3, then 2, then 1, decreasing i each time until i is 0.
Explain how a while loop works and why updating the loop variable is important.
Think about what happens if the condition never changes.
You got /3 concepts.
Write a simple example of a while loop that counts down from 5 to 1 and prints each number.
Start with int i = 5; then use while (i > 0).
You got /4 concepts.