Game Development Reference
In-Depth Information
Let's start by explaining what goes on in the for loop.
We start by writing for to define that this is a for loop. Next, we have a set of three es-
sential parts to the loop.
1. i=0; sets a variable i to be equal to 0. This part has a semicolon at the end to
define its end in the loop structure.
2. i<10; is our check. We check to see whether i is lower than 10. As it was set to
0 earlier, this is true. This part also has a semicolon at the end to define its end in
the loop structure.
3. i++ : ++ adds 1 to whatever variable is using it. In this case, it adds 1 to i . This
part has no semicolon at the end; this is important. Adding one will cause an error
in the game.
The preceding three steps are how all for loops are structured. However, any variable
name can be used.
Basically, we set a variable to a number to start with. We then check to see if this number
is equal, greater than, or lower than another number. Then, finally, we tell the loop what to
do at the end. In this case, we add 1 to the variable and run the loop again if the variable is
still lower than 10. You may also count down.
Whatever code is in the curly braces that follow will be executed every time the loop runs.
The preceding code sets an array's value to 5 . You can see that no index number is used
for the array and instead, we are using the i variable.
As i starts off being equal to zero, on the first run, the index number for the array is also
0. 1 is then added to i , making the index number equal to 1 in the second run, and so on
through the rest of the loop.
Search WWH ::




Custom Search