In this lesson, we will learn about the C++ do-while loop with a few examples to better understand the topic.
The basic syntax of the do-while loop is:
Basic syntax
do { // body of do while loop; } while (condition);
The ‘do..while’ body is executed at least once before the condition is tested, distinguishing it from the while loop in one vital way.
In the basic syntax of the do while loop,
Example
//Program prints 3 integers #include <iostream> using namespace std; int main() { int number = 3; do { cout << number << " "; number--; } while (number >= 1); return 0; }
Output
3 2 1
In this case, the do..while loop continues until the number >1. The loop ends when the value is 0.
That’s how the program performs
Variant | Variable Update | number >= 1 | Action |
---|---|---|---|
1st | number = 3 | True | 3 is printed. The number is decreased to 3. |
2nd | number = 2 | True | 2 is printed. The number is decreased to 2. |
3rd | number = 1 | True | One is printed. The number is decreased to 1. |
4th | number = 0 | false | Program terminated |
This concludes the C++ do while loop lesson. The next lesson will teach about the break Statement in C++.