CSE 111
Karel the Robot
Loops
Repeating a sequence of instructions
Unconditional
Repeat a set number of times
ITERATE
Conditional
Repeat while a condition is true
WHILE…DO
Unconditional Loops
Format
ITERATE positive-number TIMES
BEGIN
Body of loop (sequence of instructions)
END;
How does it work?
Repeat the body of the loop a given number of
times
New Reserved Words
ITERATE
TIMES
Unconditional Loops
Example
Let’s rewrite the turnright instruction
Original Definition
DEFINE-NEW-INSTRUCTION turnright AS
BEGIN
turnleft;
turnleft;
turnleft;
END;
New Definition
DEFINE-NEW-INSTRUCTION turnright AS
BEGIN
ITERATE 3 TIMES
BEGIN
turnleft;
END;
END;
Conditional Loops
Format
WHILE condition DO
BEGIN
Body of loop (sequence of instructions)
END;
How does it work?
Repeat the body of the loop while the given
condition is met
Conditions are the same as the conditions for
IF/THEN/ELSE
New Reserved Words
WHILE
DO
Conditional Loops
Condition is checked BEFORE loop body is
executed
It is possible that the loop body may never be
executed
Constructing WHILE DO loops
Identify condition for which loop should terminate
Negate termination condition for loop condition
Determine what must be done before and after the
loop
Perform minimal number of instructions in the
loop
Conditional Loop Example
Task
Put down a line of beepers, between Karel & the
closest wall in front of Karel
Initial World
Streets
Karel starts with 10 beepers in bag
10
9
8
7
6
5
4
3
2
1
N
W
E
S
Karel’s Initial
Position
(facing east)
1 2 3 4 5 6 7 8 9 10
Avenues
Conditional Loop Example
Streets
Final World
10
9
8
7
6
5
4
3
2
1
N
W
E
S
1 1 1 1 1 1 1 1
Karel’s Final
Position
1 2 3 4 5 6 7 8 9 10
Avenues
Conditional Loop Example
BEGINNING-OF-PROGRAM
BEGINNING-OF-EXECUTION
putbeeper;
WHILE front-is-clear DO
BEGIN
move;
putbeeper;
END;
turnoff;
END-OF-EXECUTION
END-OF-PROGRAM
Conditional Loop Example
Streets
What happens if the initial world is as shown
below?
10
9
8
7
6
5
4
3
2
1
N
W
E
S
Karel’s Initial
Position
(facing east)
1 2 3 4 5 6 7 8 9 10
Avenues
References
Richard E. Pattis (revised by Jim Roberts &
mark Stehlik), Karel the Robot, John Wiley &
Sons, Inc., 2nd edition, 1995, pp 93-115