C++ course menu
C++ while and do-while Loops: Conditions, Input Validation and Sentinels
Master C++ while and do-while loops: loops driven by conditions, digit-processing loops, sentinel values, validating user input with cin.clear and cin.ignore, menus with do-while, and avoiding infinite loops.
On this page
A for loop is ideal for counting. A while loop is ideal when you repeat until something happens: a balance reaches a target, a number runs out of digits, or the user types a valid answer.
while: check first, then run#
#include <iostream>
int main() {
int countdown = 3;
while (countdown > 0) {
std::cout << countdown << "...\n";
--countdown;
}
std::cout << "Lift off!\n";
}3...
2...
1...
Lift off!The condition is tested before each repetition. If it is false at the start, the body runs zero times.
Processing digits#
Many number problems peel off the last digit with % 10 and remove it with / 10, until nothing is left. You do not know in advance how many digits there are, so while fits:
#include <iostream>
int main() {
int n = 50721;
int digit_sum = 0;
int reversed = 0;
while (n > 0) {
int digit = n % 10;
digit_sum += digit;
reversed = reversed * 10 + digit;
n /= 10;
}
std::cout << "Digit sum: " << digit_sum << '\n';
std::cout << "Reversed: " << reversed << '\n';
}Digit sum: 15
Reversed: 12705Sentinel values#
A sentinel is a special value that means "stop". For example, read prices until the user types 0:
#include <iostream>
int main() {
double total = 0;
double price = 0;
std::cout << "Enter prices (0 to finish):\n";
std::cin >> price;
while (price != 0) {
total += price;
std::cin >> price;
}
std::cout << "Total: " << total << '\n';
}Enter prices (0 to finish):
120
80
45
0
Total: 245Notice the pattern: read once before the loop, then read again at the end of each repetition, so the sentinel is never added to the total.
do-while: run first, then check#
The body of a do ... while always runs at least once, which is exactly what menus need: show the menu, then decide whether to show it again.
#include <iostream>
int main() {
int choice = 0;
int counter = 0;
do {
std::cout << "1) Add one 2) Quit: ";
std::cin >> choice;
if (choice == 1) {
++counter;
std::cout << "Counter is " << counter << '\n';
}
} while (choice != 2);
std::cout << "Final value: " << counter << '\n';
}1) Add one 2) Quit: 1
Counter is 1
1) Add one 2) Quit: 1
Counter is 2
1) Add one 2) Quit: 2
Final value: 2Robust input validation#
When a user types text where a number is expected, std::cin enters a fail state and stops reading. To recover and ask again you must:
std::cin.clear()to reset the fail state;std::cin.ignore(...)to throw away the bad input on that line.
#include <iostream>
#include <limits>
int main() {
int age = 0;
while (true) {
std::cout << "Age: ";
if (std::cin >> age && age > 0 && age < 130) {
break; // valid: leave the loop
}
std::cout << "Please enter a whole number between 1 and 129.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Thank you. You are " << age << ".\n";
}Age: abc
Please enter a whole number between 1 and 129.
Age: -5
Please enter a whole number between 1 and 129.
Age: 30
Thank you. You are 30.while (true) with a break on success is a clear way to write "keep asking until it is right". See break and continue.
Avoiding infinite loops#
Every while loop needs something inside it that eventually makes the condition false. Check these three things when a loop never ends:
- Is the loop variable updated inside the body?
- Is it updated in the right direction (
++vs--)? - Can the condition actually become false?
while (x != 10)withx += 3starting from 0 skips over 10 and never stops;while (x < 10)is safer.
Common mistakes#
Practice#
Practice exercise
Write a program that counts how many digits are in int n = 9040017; using a while loop. Make sure your program would also report 1 for n = 0.
Show hint
A do ... while runs at least once, which handles 0 naturally.
Show solution
#include <iostream>
int main() {
int n = 9040017;
int digits = 0;
do {
++digits;
n /= 10;
} while (n != 0);
std::cout << digits << '\n';
}7With a plain while (n > 0) loop, n = 0 would give 0 digits.
Practice exercise
The Collatz sequence starts from a number n: if n is even, halve it; if odd, make it 3n + 1; stop when it reaches 1. Print the sequence for n = 6 and the number of steps.
Show solution
#include <iostream>
int main() {
int n = 6;
int steps = 0;
std::cout << n;
while (n != 1) {
if (n % 2 == 0) {
n /= 2;
} else {
n = 3 * n + 1;
}
std::cout << ' ' << n;
++steps;
}
std::cout << "\nSteps: " << steps << '\n';
}6 3 10 5 16 8 4 2 1
Steps: 8Key takeaway#
Finished this lesson?