Iterative Statement : While Loop

The while loop.

As mentioned earlier, the while loop is an entry controlled loop. The syntax of a while loop is

while (condition) statement

and its function is simply to repeat statement while expression is true. While is a reserved word of C++; condition is a Boolean expression; and statement can be simple or compound statement.

For example, we are going to make a program to count down using a while loop:

// custom countdown using while

#include <iostream.h>

int main ()

{

int n;

cout << "Enter the starting number > ";

cin >> n;

while (n>0)

{

cout << n << ", ";

--n;

}

cout << "SHOOT!";

return 0;

}

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n be greater than 0 ), the block of instructions that follows will execute an indefinite number of times while the condition (n>0) remains true. All the process in the program above can be interpreted according to the following script: beginning in main:

    • User assigns a value to n.

    • The while instruction checks if (n>0). At this point there are two possibilities:

        • true: execute statement (step 3,)

      • false: jump statement. The program follows in step 5..

Execute statement:

cout << n << ", ";

--n;

(prints out n on screen and decreases n by 1).

End of block. Return Automatically to step 2.

Continue the program after the block: print out SHOOT! and end of program.

We must consider that the loop has to end at some point, therefore, within the block of instructions (loop's statement) we must provide some method that forces condition to become false at some moment, otherwise the loop will continue looping forever. In this case we have included --n; that causes the condition to become false after some loop repetitions: when n becomes 0, that is where our countdown ends.

HOME LEARN C++ PREVIOUS NEXT