Graphics Programs Reference
In-Depth Information
lest it continue into infinity. A while loop says to execute the following set of
instructions in a loop while a condition is true. A simple program for a hungry
mouse could look something like this:
While (you are hungry)
{
Find some food;
Eat the food;
}
The set of two instructions following the while statement will be repeated
while the mouse is still hungry. The amount of food the mouse finds each
time could range from a tiny crumb to an entire loaf of bread. Similarly, the
number of times the set of instructions in the while statement is executed
changes depending on how much food the mouse finds.
Another variation on the while loop is an until loop, a syntax that is
available in the programming language Perl (C doesn't use this syntax). An
until loop is simply a while loop with the conditional statement inverted. The
same mouse program using an until loop would be:
Until (you are not hungry)
{
Find some food;
Eat the food;
}
Logically, any until-like statement can be converted into a while loop.
The driving directions from before contained the statement Continue on
Main Street until you see a church on your right. This can easily be changed into a
standard while loop by simply inverting the condition.
While (there is not a church on the right)
Drive down Main Street;
0x233
For Loops
Another looping control structure is the for loop . This is generally used when
a programmer wants to loop for a certain number of iterations. The driving
direction Drive straight down Destination Road for 5 miles could be converted to
a for loop that looks something like this:
For (5 iterations)
Drive straight for 1 mile;
In reality, a for loop is just a while loop with a counter. The same state-
ment can be written as such:
Set the counter to 0;
While (the counter is less than 5)
Search WWH ::




Custom Search