next up previous
Next: Example while loop: Printing Up: Introduction to C++ Programming Previous: Exercises

The while statement

The following piece of C++ illustrates a while statement. It takes a value entered by the user and as long as the user enters positive values it accumulates their sum. When the user enters a negative value the execution of the while statement is terminated.

sum = 0.0;
cin >> x;
while (x > 0.0)
   {
    sum += x;
    cin >> x;
   }

The variable sum which is to hold the accumulated sum is initialised to zero. Then a value for x is entered so that x has a value before being tested in the condition x > 0.0. Note that the value of x is updated in the body of the while loop before returning to test the condition x > 0.0 again.

The general form of a while statement is:

      while (  condition  )
         statement
While the condition is true the statement is repeatedly executed. The statement may be a single statement (terminated by a semi-colon) or a compound statement. Note the following points:
  1. It must be possible to evaluate the condition on the first entry to the while statement. Thus all variables etc. used in the condition must have been given values before the while statement is executed. In the above example the variable x was given a value by entering a value from the user.
  2. At least one of the variables referenced in the condition must be changed in value in the statement that constitutes the body of the loop. Otherwise there would be no way of changing the truth value of the condition, which would mean that the loop would become an infinite loop once it had been entered. In the above example x was given a new value inside the body of the while statement by entering the next value from the user.
  3. The condition is evaluated before the statement is executed. Thus if the condition is initially false then the statement is never executed. In the above example if the user entered a negative number initially then no execution of the body of the while loop would take place.



Subsections
next up previous
Next: Example while loop: Printing Up: Introduction to C++ Programming Previous: Exercises
Peter JB King
1999-08-31