Tutorial Details:
Difficulty Level:
Intermediate
Topics Covered: Using
loops in NQC.
Assumed Knowledge:
The Basics, My First Program
Written By: BILL LANE
Print Version
In our continuing series on common programming structures
this tutorial is all about looping. Running a loop allows
us to run through a series of commands for a fixed number
of times or indefinitely. There are a couple of reasons why
we might want to do this. For a start if we want to run a
sequence of commands more than once we might want to use a
repeat, rather than write
the same code multiple times. Let's look at an example:
repeat(5)PlaySound(1);
This code runs the PlaySound(1) command 5 times and then
ends. The result is five beeps in quick succession. Note that
the number 5 could be replaced with an expression. For example,
it could be replaced with Random(5)
so it selects a different number each time it executes. It
would look like this:
repeat(Random(10))PlaySound(1);
A variation of this is to use while.
While states a condition
and tells the commands to continue executing until that condition
is false:
while(myVariable == 5){PlaySound(1);}
As with other conditional forms equals can be replaced with
greater than, less than or not equal to. The while
loop can be easily turned into an infinite loop by replacing
the condition with the word true.
Because true will always
evaluate as true the while
statement will never stop looping.
A variation of while
is the do-while loop.
It looks like this:
do{
PlaySound(1);
Wait(50);
}
while(myVariable != 5);
This is very similar to the while
statement. With one main difference. The do
statement executes the commands at least once before evaluating
the condition. The while
statement evaluates the condition first and therefore may
never execute the commands. The other thing to note is that
both the do-while and
while statements evaluate
the entire expression on every pass through the loop (checking
for a change in the condition) while the repeat
statement evaluates the expression once and then executes
the commands the stated number of times.
Well that just about covers it. We've looked at using
repeat to repeat a series of commands a fixed number
of times. We've used while
and do-while to loop until
a condition is false.
|