0
0
C++programming~5 mins

While loop in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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++?
ARuns code only if condition is false
BRepeats code while a condition is true
CRuns code once regardless of condition
DStops the program immediately
What happens if the while loop condition is false at the start?
AThe loop runs once
BThe program crashes
CThe loop runs infinitely
DThe loop does not run at all
Which of these can cause an infinite while loop?
AUpdating the loop variable correctly
BUsing a for loop instead
CCondition always true and no variable update
DCondition false at start
How do you usually stop a while loop?
ABy making the condition false inside the loop
BBy restarting the program
CBy using a break outside the loop
DBy ignoring the condition
What is the output of this code? int i = 3; while (i > 0) { std::cout << i << " "; i--; }
A3 2 1
B1 2 3
C0 1 2
DNo output
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.