The <I>for</I> Loop


You may have been wondering about where the for loop has gone to. Don't worry, it's still alive and well. Unfortunately, it's changed a lot in C++. It may look very strange at first, but once you get used to it, you'll find it very powerful.

Before we get into C++'s version, let's review how Pascal does it. Take a look at this example:

for i := 1 to 10 do
begin
   foo := foo + 1;
end;

In the above example, there are 3 critical steps:

  1. i is set at 1.
  2. The block it runs is loop, and i is incremented by 1 each time.
  3. When i reaches 10, the for loop exits.

If you think about a for loop in this way, the following shouldn't be too hard to learn. Let's look at how the above loop would be done in C++:

for (i = 0 ; i < 10 ; i = i + 1)
{
   foo = foo + 1;
} 

That should probably be very confusing; Let's go over what is going on. Inside the parentheses after the for keyword, there are 3 parts.

The first part is where you initialize a counter. In our case, we're setting i to 0. This section is only run once, when the for loop starts.

The second part is the conditional statement that determines whether or not the loop will be run again. It is checked after the code under the for statement is executed. In Pascal, there was a high and low value, and that was the only way you could do it. Now, you can do anything to determine whether or not a for loop exits, as long as it uses the concept of TRUE (non-zero) or FALSE (zero).

The third part is the section that increments values. It is run right before the conditional statement. In our case above, we simply added 1 to i. You could, if you wanted, add 2 every loop, or 3, or multiply by 4, and so on.

In short, the sequence of events is:

  1. The Initializing Statement is ran. (Above, "i = 0")
  2. The Conditional Statement is checked. If it's FALSE (aka zero), the loop ends. (Above, "i < 10")
  3. The block of code inside the for loop is ran.
  4. The Incrementing Statement is ran. (Above, "i = i + 1;")
  5. Start back on step 2. (ie, run the code again)


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