Repeating Instructions
How can I get Karel to do something over and over again?
One way to get Karel to repeat an instruction over and over again is
with the ITERATE
instruction. The following program gets
Karel to move forward and pick a beeper 5 times.
BEGINNING-OF-PROGRAM
BEGINNING-OF-EXECUTION
ITERATE 5 TIMES
move
pickbeeper
END
turnoff
END-OF-EXECUTION
END-OF-PROGRAM
The instructions between TIMES
and END
are executed
the specified number of times (in this case, 5 times). This program has
the same behavior as the following program:
BEGINNING-OF-PROGRAM
BEGINNING-OF-EXECUTION
move
pickbeeper
move
pickbeeper
move
pickbeeper
move
pickbeeper
move
pickbeeper
turnoff
END-OF-EXECUTION
END-OF-PROGRAM
Iterating based on a test function
You can control iteration with a test function if you use the
WHILE
instruction. The following
instruction definition
will make Karel search forward until he finds a beeper:
DEFINE-NEW-INSTRUCTION search-for-beeper AS
WHILE not-next-to-a-beeper DO
move
END
END
This document is copyright 1994 by Joseph N. Wilson.
$Id$