In our previous tutorial, we learned about C++ If Statements which introduced us to the idea of control flow and conditions. Today, we introduce the while loop.
The While Loop
The while loop is another control flow structure that allows the programmer continuously execute a block of instructions until a specific condition is met. Below is an example of a program that contains a while loop. The idea of the program is for the user to input a variable n, and the while loop will continuously print out and increase n until it is over 100.

Now that you understand the diagram, take a look at the syntax.
while ( condition ) { // Statements } |
With the previous diagram, let’s make the program that increases and prints out n until it reaches 100.
In order to become a programmer, its essential that you learn how to create a program based on a specification. So its good to try it out on your own before you look at the solution below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Creating and initializing n int n = 0; // User prompt cout << "Please enter a number to count to 100: "; cin >> n; // Beginning of while loop while ( n < 100 ) { // Printing out n cout << n << endl; // Increasing n n = n + 1; } // End of While Loop // Program continues |
Going further with While Loops
Now that you learned how to create while loops, let’s have some more practice.
- Add to the previous program an if statement that determines if the user entered a negative number. If they did, output a message and set n to 0 so it only counts from a positive number to 100.
- Make a while loop that prints a number from a user inputted n, to 0. If the number is below zero, let the user know, and set n to 100.
- Using nested while loops, create a program that asks the user for a number from 0 – 10.
Then print out n stars on one line and print out n number of lines. For example,
n = 3
***
***
***
n = 2
**
**
