Game Development Reference
In-Depth Information
The output from this code would be
12345
as the variable i starts with a value of 1, is then printed, has one added to the
value, and is printed again five times. Imagine printing out all the numbers
between 1 and 100. It would be a lot of code.
Enter the for loop. The for loop reduces such repetitive tasks down into a few
simple lines. The basic format of a for loop is shown in Listing 1.19 .
Listing 1.19 A for Loop
for( initialize variable; test value; update value)
{
//perform some action while the test is true
}
The first part of the for loop declares a variable and gives it an initial value. The
second part performs a Boolean test on the value of the variable. If the test
comes back true, the loop performs the code inside the parentheses. After the
contents of the parentheses are finished, the variable value is updated and the
test is performed again; if true, the inside part runs again. This continues until
the test becomes false and the loop quits.
A for loop to perform the same action as Listing 1.18 is shown in Listing 1.20 .
Listing 1.20 A for Loop to Print out Numbers between 1 and 5
for( var i:int = 1; i <= 9; i++)
{
print(i);
}
Note
Listing 1.20 introduces a new type of arithmetic used as a shortcut
in programming. Writing
i++
is identical to writing
i = i + 1
It is a shortcut for adding one to the value of a variable. You can also write
i--
which will take one away from the variable i. More shortcut arithmetic
is shown in Table 1.4 .
Search Nedrilad ::




Custom Search