In this lesson, you will learn about C++ while loop with a few examples.
Below is the syntax of the while loop in C++
Basic syntax
while (condition) { // body of the while loop }
In the basic syntax of the while loop,
Example
//Program prints 3 integers #include <iostream> using namespace std; int main() { int number = 3; while (number >= 1) { cout << number << " "; number--; } return 0; }
Output
3 2 1
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++ while loop lesson. The next lesson will learn about the “do while” in C++.