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:
- i is set at 1.
- The block it runs is loop, and i is incremented by 1 each time.
- 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:
- The Initializing Statement is ran. (Above, "
i = 0 ")
- The Conditional Statement is checked. If it's FALSE (aka zero), the loop ends. (Above, "
i < 10 ")
- The block of code inside the
for loop is ran.
- The Incrementing Statement is ran. (Above, "
i = i + 1; ")
- Start back on step 2. (ie, run the code again)
|