Game Development Reference
In-Depth Information
int
i;
i=beginvalue ;
while
(i < endvalue )
{
dosomethingusefulusingi
i++;
}
Because this kind of instruction is quite common, a more compact notation is avail-
able for it:
int
i;
for
(i = beginvalue ;i<endvalue;i++)
{
dosomethingusefulusingi
}
The meaning of this instruction is exactly the same as the earlier
while
-instruction.
The advantage of using the
for
-instruction in this case is that everything that has
something to do with the counter is nicely grouped together in the header of the
instruction. This reduces the chance that you forget the instruction to increment
the counter (resulting in an endless loop). In the cases where 'do something useful
using
i
' consists of only a single instruction, you can leave out the braces, which
makes the notation even more compact. Also, you can put the declaration of the
variable
i
in the header of the
for
-instruction as well. For example, have a look at the
following code fragment:
for
(
int
i=0; i < lives; i++)
spriteBatch.Draw(livesSprite,
new
Vector2(i
∗
livesSprite.Width + 15, 20),
Color.White);
This is a very compact instruction that increments the counter and draws the sprite
at different positions. This instruction is equivalent to the
while
-instruction:
int
i=0;
while
(i < numberOfLives)
{
∗
livesSprite.Width, 20), Color.White);
spriteBatch.Draw(livesSprite,
new
Vector2(i
i=i+1;
}
And another example:
−
1; i >= 0; i
−−
)
spriteBatch.Draw(livesSprite,
new
Vector2(i
for
(
int
i = lives
∗
livesSprite.Width + 15, 20),
Color.White);