C++ While and Do-While Loops
A loop repeats a block of code. while and do-while loops repeat as long as a condition is true, which suits work where the number of rounds is not known in advance.
while
while checks its condition before each round:
#include <iostream>
int main() {
int n = 5;
while (n > 0) {
std::cout << n << "... ";
n--;
}
std::cout << "Lift off!\n";
return 0;
}5... 4... 3... 2... 1... Lift off!
The loop needs three things: a starting value (n = 5), a condition that uses it (n > 0), and a change in the body (n--). Without the change the loop never ends; press Stop in the editor to end such a program.
Reading until a stop value
#include <iostream>
int main() {
int number, total = 0, count = 0;
std::cout << "Numbers, 0 to stop:\n";
while (std::cin >> number && number != 0) {
total += number;
count++;
}
std::cout << count << " numbers, total " << total << "\n";
return 0;
}4 10 7 0
Numbers, 0 to stop: 3 numbers, total 21
std::cin >> number is part of the condition: the loop also stops when the input ends or is not a number.
do-while
do-while checks its condition after each round, so the body always runs at least once. That fits menus, which must be shown before the user can choose:
#include <iostream>
int main() {
int choice;
do {
std::cout << "1) Say hello 2) Quit: ";
std::cin >> choice;
if (choice == 1) std::cout << "Hello!\n";
} while (choice != 2);
std::cout << "Bye\n";
return 0;
}1 1 2
1) Say hello 2) Quit: Hello! 1) Say hello 2) Quit: Hello! 1) Say hello 2) Quit: Bye
Note the semicolon after while (...) at the end of a do-while.
Which loop to choose
for(next topic): you know how many rounds, or you visit every element of a collection.while: repeat until something happens, such as reading until the user stops.do-while: the body must run at least once.
All of them can express the same work; picking the one that matches the intention makes code easier to read.
Practice exercises
- Print the even numbers from 2 to 20 with a
whileloop. - Read numbers until a negative one and print the largest.
- Write a number guessing game with
do-whilethat ends when the guess is right.