C++ while and do while Loop
Use while when you repeat until a condition changes, and you do not know the count.
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << "i = " << i << '\n';
i++;
}
}
Output
i = 1
i = 2
i = 3
i = 4
i = 5
do while: at least one time
#include <iostream>
int main() {
int i = 10;
do {
std::cout << "Runs once, i = " << i << '\n';
i++;
} while (i < 5);
while (i < 5) {
std::cout << "never printed\n";
}
std::cout << "done\n";
}
Output
Runs once, i = 10
done
Digits of a number
#include <iostream>
int main() {
int number = 9475, sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
std::cout << "Sum of digits: " << sum << '\n';
}
Output
Sum of digits: 25
Ask until the input is valid
#include <iostream>
#include <limits>
int main() {
int age = -1;
while (age < 0 || age > 120) {
std::cout << "Age: ";
if (!(std::cin >> age)) {
std::cin.clear(); // reset the fail state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // throw away the bad line
age = -1;
}
}
std::cout << "\nSaved: " << age << '\n';
}
Output
Age: Age: Age:
Saved: 20
for or while?
| Loop | Use when |
|---|---|
| for | You count, or you know the number of rounds |
| while | You repeat until a condition is false |
| do while | The body must run at least once (menus, input) |
Infinite loops
while (true) {
// runs for ever: use break to leave
}
Note:
The most common bug is forgetting to change the variable in the condition, so the loop never ends. Next: C++ break and continue.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |