Learn C++ · lesson 18 of 61 · about 8 minutes
while and do-while
Let the hero rest at an inn while it helps and the gold lasts: repeat code while a condition is true, and run a body at least once with do-while.
What you'll learn
- Write a while loop
- Write a do-while loop
- Avoid infinite loops
A night at the inn
After the doors, the hero is hurt. The inn charges 5 gold a night, and each night heals 10 health, up to the maximum. The hero should keep resting while it helps and they can pay for it, but nobody knows in advance how many nights that will be. That's the job of a while loop.
Check, then run
while (cond) { ... } checks the condition before every lap. Something in the body must eventually make it false. do { ... } while (cond); runs the body first, so it always runs at least once.
while
#include <iostream>
int main() {
int fuel = 3;
while (fuel > 0) {
std::cout << "Fuel: " << fuel << "\n";
fuel--;
}
std::cout << "Empty\n";
}Output
Fuel: 3
Fuel: 2
Fuel: 1
EmptyStep through it: two nights at the inn
#include <iostream>
int main() {
int health = 80;
int gold = 12;
while (health < 100 && gold >= 5) {
gold -= 5;
health += 10;
std::cout << "Health: " << health << ", Gold: " << gold << "\n";
}
std::cout << "You set off again.\n";
}Output
Health: 90, Gold: 7
Health: 100, Gold: 2
You set off again.do-while: ask until valid
#include <iostream>
int main() {
int n;
do {
std::cout << "Pick 1-3: ";
std::cin >> n;
} while (n < 1 || n > 3);
std::cout << "\nYou picked " << n << "\n";
}Output
Pick 1-3: Pick 1-3: Pick 1-3:
You picked 2while or do-while?
Use while when the body might not need to run at all: a hero with full health shouldn't pay for a night. Use do-while when the body has to run before there's anything to check, like asking a question before you can test the answer.
Tip
Check every way out of a loop. The inn loop ends when health is full or the gold runs out, and each night moves at least one of them closer.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.