The while loop
The while
loop is used to run a section of the code repeatedly. This is useful if you have a set of actions that must be done repeatedly to accomplish some goal. For example, the while
loop in the following code repeatedly prints the value of the variable x
as it is incremented from 1 to 5:
int x = 1; while( x <= 5 ) // may only enter the body of the while when x<=5 { cout << "x is " << x << endl; x++; } cout << "Finished" << endl;
This is the output of the preceding program:
x is 1 x is 2 x is 3 x is 4 x is 5 Finished
In the first line of code, an integer variable x
is created and set to 1. Then, we go the while
condition. The while
condition says that while x
is less than or equal to 5, you must stay in the block of code that follows.
Each iteration of the loop (an iteration means going once around the loop) gets a little more done from the task (of printing the numbers 1 to 5). We program the loop to automatically...