How can we have Karel execute some instruction
n ² times (where n
² = n * n; e.g., 3 ² = 3*3 = 9)?
ANSWER:
iterate <n> times
iterate <n> times
<instruction>
e.g.) to have Karel move 3*3=9 times, could do:
iterate
3 times
iterate 3 times
move
OR:
iterate
9 times
move
Which
is "better"? Well, clearly the second
is simpler (& even faster to execute (why?)).
But
the first one makes it clearer that we
are more interested in Karel moving 3*3
times than in Karel moving 9 times.
In
Pascal, we'll have "variables" that allow
the user to specify how many times an
instruction should be executed without
changing the program, so to do something
n^2 times, where the user decides each
time what n is, we would have to use a
Pascal version of the first, "nested", iterate
instruction.
Just
for the record, Pascal's version of the iterate loop
called a "for" loop, but we probably won't cover it.
For more information, see Biermann, p. 303.
b) To have Karel repeat something an indefinite
number of times, as long
as some condition
is true, use a "while" loop:
* syntax
(= last clause of our recursive definition of
instruction):
WHILE
<test> DO
<instruction>
isdef an instruction
* semantics:
(best given by a flowchart; see
Lecture
Notes #4)
First, Karel decides if <test> is true.
If it is, then Karel executes <instruction>.
Karel repeats the previous 2 steps
until <test> is false.
When <test> is false,
Karel does NOT execute <instruction>;
instead, he goes on to the next instruction.
Note:
If, for some reason, <test> is always
true,
then Karel is in an infinite loop!
e.g.) Suppose Karel is inside a rectangular room
of any size, with no doors, initially located
at the lower left corner of the room, facing E.
Suppose
we want Karel to walk around the
room, next to the wall, & stop at his starting
place.
Solution:
iterate 4 times
begin
while front-is-clear do
move;
turnleft
end
TRY IT!
* In a while-loop:
- Karel
keeps doing <instruction> WHILE
<test> is true.
QUESTION:
What does Karel do in the following
example (assume that "face-east"
& "dance-a-jig" have been defined
as new instructions earlier in the
program)?
face-east;
while not-facing-east do
if next-to-a-beeper
then pickbeeper
else begin
if any-beepers-in-beeper-bag
then putbeeper
else move
end;
dance-a-jig
TRY IT!
(Answer: Karel dances a jig!!)
i.e.) if
<test> is false,
then <instruction> is NOT done
i.e.)
<test> is tested BEFORE <instruction>
is executed
- QUESTION:
How
can you use a while-loop to make
Karel face east?
ANSWER:
See
Lecture
Notes #11 :-)