C++: While Loops
When creating applications in C++, it's often extremely useful to be able to use the programming concept of a loop. This is a piece of code that repeats while a certain condition is true. In this tutorial, we will be learning how to use the while loop.
The while loop is the simplest of loops in C++ and pretty much does exactly what we defined in the basic introductory paragraph. It loops a piece of code while a certain condition is true. The loop is created using the while keyword, followed by a condition in brackets (you already know how to formulate these – they are exactly as found in if statements!), followed by the code you want to execute in curly brackets. Remember that we can also use a bool value as the condition if we want -- as in if statements, it's all about whether true or false is returned.
So let's get some test code running. One of the simplest (and most common) examples in C++ is simply counting up numbers. If we create an integer variable and set it to 0, create a while loop that executes code while the number is less than or equal to 5, output the integer variable in the loop and then add one to the number during the loop – we should have a loop that goes round 5 times and counts up to 5 (think about it, the logic all makes sense). The code might be something like the following:
int number = 1;
while(number <= 5)
{
cout << number << endl;
number = number + 1;
}
On running this code, you should see that it all works as planned! The program counts up from 1 to 5 and hence the loop and condition were formulated correctly. It's worth noting that adding one to the variable is called 'incrementing' it, and can be accomplished via many methods (number = number + 1, number += 1; and some other we'll cover in the future).
Obviously loops aren't only useful for counting up numbers (although they are very good at that, as we've seen!) -- let's say we wanted to only move the program on after the user had entered a 'valid' number into the program for example. We could create a loop that only breaks after the input has been validated! Booleans (bools) serve a perfect purpose for this, and so we could do something like this:
bool valid_input = false; //If the input is valid
int input; //Integer to hold the user input
while(!valid_input) //While the input is not valid
{
cout << "Enter a number between 1 and 50: ";
cin >> input;
if(input >= 1 && input<=50) //Is the input valid?
{
valid_input = true; //Set 'valid_input' to true to break from the loop
}
}
It's worth noting that the code above could also work by using while(true) (an infinite loop) and then using break; to break out of the loop if the input is valid.
Back to C++

