for
A for loop performs initialization
before the first iteration. Then it performs conditional testing and, at the end
of each iteration, some form of “stepping.” The form of the
for loop is:
for(initialization; conditional; step)
statement
Any of the expressions
initialization,
conditional, or step
may be empty. The initialization code executes once at the very
beginning. The conditional is tested before each iteration (if it
evaluates to false at the beginning, the statement never executes). At the end
of each loop, the step executes.
for loops are usually used for
“counting” tasks:
//: C03:Charlist.cpp
// Display all the ASCII characters
// Demonstrates "for"
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 128; i = i + 1)
if (i != 26) // ANSI Terminal Clear screen
cout << " value: " << i
<< " character: "
<< char(i) // Type conversion
<< endl;
} ///:~
You may notice that the variable i
is defined at the point where it is used, instead of at the beginning of the
block denoted by the open curly brace ‘{’. This is in
contrast to traditional procedural languages (including C), which require that
all variables be defined at the beginning of the block. This will be discussed
later in this
chapter.