- QUESTION:
How
can you use a while-loop to make
Karel face east?
ANSWER:
When
a while-loop is exited,
the <test> has become false.
Therefore,
can use while-loops to make
a certain condition false
(& therefore make its opposite true)
So,
here are 3 possible definitions of
the new instruction "face-east":
the old one:
define-new-instruction face-east as
begin
if not-facing-east
then turnleft;
if not-facing-east
then turnleft;
if not-facing-east
then turnleft
end
And here's a shorter one:
define-new-instruction face-east as
iterate 3 times
if not-facing-east
then turnleft;
But
here's the best one:
define-new-instruction face-east as
while not-facing-east do
turnleft;
When
this is executed,
the test becomes false,
so it makes Karel face east!
Note
that all 3 of these versions of
"face-east" are equivalent in the sense that
Karel's behavior is the same,
but his method (= algorithm) is different
16. A longer top-down design & stepwise
refinement example:
See Otterbein
Lecture 17.