Small Steps I — Creating with Text and Numbers
Repeating while a condition holds
Print backwards from 5 to 1.
What you will learn
while repeats the code inside braces while its condition is true. It checks the condition before every iteration.
Try it
Example · example.cpp
void small_main()
{
int count = 3;
while (count > 0)
{
print(count);
count = count - 1;
}
}
The loop ends when count becomes 0. If it starts at 0, nothing is printed. Removing the line that decreases count makes the loop run forever; use the IDE's Stop button in that case.
for is convenient when counting iterations; while is convenient when waiting for a condition to change.
Expected output:
3
2
1
Exercise
Print backwards from 5 to 1.
Exercise starter · exercise_starter.cpp
void small_main()
{
int count = 3;
while (count > 0)
{
print(count);
count = count - 1;
}
}
Hint
Change the parts of the example that you need.
show solution
void small_main()
{
int count = 5;
while (count > 0)
{
print(count);
count = count - 1;
}
}