The <I>while</I> Loop


Now that we've gone over making choices in a program, it's time to think about making a program that can loop. Let's start with the while loop. You may remember this from Pascal, where you would say something like:

a := 0;
while (a < 20) do
  a := a + 1;

This would of course loop 20 times, each time incrementing a by one. C++, in a similar manner as with if, removes some of the fat and makes you add parentheses to the statement used to determine if the loop should keep going (called the conditional statement). Take a look at the above statement in C++ form:

a = 0;
while (a < 20)
  a = a + 1;

Notice how the conditional statement, "a < 20", is surrounded in perentheses, just like you had to do with the if statement. Also, note that the do keyword was removed. You may be noticing a trend away from Pascal's English-like syntax into a more cryptic, terse programming language. This is very much the case.

Let's try using while in a program!

void main(void)
{
   float taco;
   int chimichanga;  / mmm...chimichangas..

   taco = 22.2;
   chimichanga = 5524;


   /* This next part will keep adding
      10 to taco until taco is no longer
      less than chimichanga              */

   while (taco < chimichanga)
     taco = taco + 10;

}

The above program is pretty simple -- just two variables that get assigned two values and then are used in a while loop. You should note that, like Pascal, the order of a while loop is always:

  1. Test the conditional statement that controls the loop.
  2. If it's TRUE (ie, non-zero), execute the statement under the conditional.
  3. If not, exit the while loop.
  4. If we haven't exited the while loop yet, start back on step one.


Table of Contents

The Big Picture | Comments | Variables | More on Variables
Variable Operations | Making Choices | More on if | Using else
Using switch | The while Loop | The do..while Loop | Constants
The for Loop | More on the for Loop | Exercises