The while loop is especially useful for validating input. If an invalid value is entered, a loop can require that the user reenter it as many times as necessary. For example, the following loop asks for a number in the range of 1 through 100:
1 2 3 4 5 6 7
|
cout << "Enter a number in the range 1-100: ";
cin >> number;
while (number < 1 || number > 100)
{
cout << "ERROR: Enter a value in the range 1-100: ";
cin >> number;
}
|
This code first allows the user to enter a number. This takes place just before the loop. If the input is valid, the loop will not execute. If the input is invalid, however, the loop will display an error message and require the user to enter another number. The loop will continue to execute until the user enters a valid number.
Sometimes it’s important for a program to control or keep track of the number of iterations a loop performs. For example, the program below displays a table consisting of the numbers 1 through 10 and their squares, so its loop must iterate 10 times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// This program displays a list of numbers and
// their squares.
#include <iostream>
using namespace std;
int main()
{
const int MIN_NUMBER = 1, // Starting number to square
MAX_NUMBER = 10; // Maximum number to square
int num = MIN_NUMBER; // Counter
cout << "Number Number Squared\n";
cout << "-------------------------\n";
while (num <= MAX_NUMBER)
{
cout << num << "\t\t" << (num * num) << endl;
num++; //Increment the counter.
}
return 0;
}
|
The variable
num
, which starts at 1, is incremented each time through the loop. When
num
reaches 11 the loop stops.
num
is used as a counter variable, which means it is regularly incremented in each iteration of the loop. In essence,
num
keeps count of the number of iterations the loop has performed.
It’s important that
num
be properly initialized. Remember, variables defined
inside a function have no guaranteed starting value.