CSE 111, Fall 2000

Great Ideas in Computer Science

Lecture Notes #11

Karel the Robot (continued)

(15.  Repetition (Looping) (continued))

(b)    While-loops (continued))

    -    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.
 


Copyright © 2000 by William J. Rapaport (rapaport@cse.buffalo.edu)

file: 111F00/lecturenotes11.29sp00.html