The <I>do..while</I> Loop


You may remember Pascal's repeat..until loop that let you run essentially a while loop backwards; first the code that it should run, and then the conditional statement would be checked. Here's an example of what we're talking about:

a := 44;

repeat
  a := a + 1;
until a > 50;

This loop would run once, then check the conditional statement "a > 50". If it was TRUE, the loop would stop. If it wasn't, the loop would keep going. Simple, eh?

C++ has a fairly similar version of repeat..until called do..while. As the name suggests, the words do and while take the place of repeat and until. Another major difference is that only one statement goes between the do/while pair. Obviously, you can expand the amount of commands by using { and } to make a block of code.

a = 44;

do { / Notice the brace!

  a = a + 1;

} while (a <= 50);

One thing you might be looking strangely at is the conditional statement, "a <= 50". Why is it "less than or equal to" instead of "greater than" in the Pascal example above it? Well, the repeat..until loop goes through UNTIL the conditional statement becomes TRUE, when it exits. The do..while loop, on the other hand, is completely opposite; it continues the looping WHILE the conditional statement is TRUE. If you're at first a little confused by this sudden reversal of how it works, just read the last line over to yourself when you write your code the first couple times. Make sure it makes sense. Think of the above do..while loop as "do stuff while a is less than or equal to fifty", and it may suddenly become easier to follow.


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