A while loop says to perform a set of operations while a condition is true. It is known as a pre-test loop, because the condition is tested before the loop is run at all, meaning the body of the loop may never run.
The general form for a while loop is:
while( <condition> )
{
// loop body
}
Notice that the loop body is contained within braces. Indenting is good form, and makes your code easier to read, but is not technically required.
As with the if statement, the braces are not required for a single statement body, but it is good form to use them.
Consider the following example, where the question is asked until the correct answer is given.
#include <iostream>
#include <ctime>
#include <cstdlib>
int main() {
srand(time(0));
int num1 = rand() % 100;
int num2 = rand() % 100;
int answer;
cout << "What is " << num1 << " + " << num2 <<"?" << endl;
cin >> answer;
while(answer != num1 + num2)
{
cout << "That is incorrect, please try again. What is "
<< num1 << " + " << num2 <<"?" << endl;
cin >> answer;
}
}
Programmers can run a program until a user enters a specific value. Such an answer might be asked by: “Do you wish to continue (y/n): “.
while ( tolower(continueLoop) == 'y')
{
// loop body
}
Since the while loop can be used to run a program until a specific value is set among a series of similar values, programmers can use concept and run a program until a user enters an exit value.
This is called a sentinel loop, and the value that is checked against is called a sentinel value. Consider the example below which runs until the use enters 0;
int data;
int runningTotal = 0;
cout << "Enter a series of numbers to total. Zero (0), exits: "
cin >> data;
while (data != 0)
{
runningTotal += data;
cin >> data;
}
cout << "The total of the numbers you entered was: " << runningTotal;
The C++ While Loop was originally found on Access 2 Learn