Game Development Reference
In-Depth Information
else
{
cout << "Print This If All False!";
}
return 0;
}
We can, in fact, have as many
else if
statements as we like. The
else
statement is also optional: It
is completely valid to have cases where no
else
statement is necessary.
Now we'll take a look at the
for
loop, which allows us to execute the same code block multiple
times.
The for Loop
The
for
loop allows us to iterate as many times as necessary. Listing 6-5 shows a simple
for
loop in
action.
Listing 6-5. A
for
Loop
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
for (unsigned int i=0; i<10; ++i)
{
cout << "Loop Iteration: " << i << endl;
}
return 0;
}
The
for
loop statement consists of three parts:
An initializer, which sets the initial value of the loop index variable
(i.e.,
unsigned int i=0
).
A test, in which the loop will continue to execute until the test statement
evaluates to
false
(i.e.,
i<10
).
A continuation statement, which is executed at the end of each successful loop
before starting the next one (i.e.,
++i
).
The
for
loop in our example results in the output being printed to the console 10 times with the
values 0 through 9 appended to the end.
A more powerful example of this is to combine the
for
loop with an array, as shown in Listing 6-6.