# While loops – weeks 13 and 14

“Just keep swimming… just keep swimming…”

-Dory

Handout: 7_intro_1_while_loops

## the While loop

A solution using While loops Show it to me

A solution with a while loop is short, clear, does not waste cycles, and does not waste memory: it stops as soon as the goal is accomplished.

# solution using a while loop
def face_north():
while not is_facing_north():
left()


Recursion and while loops do the same thing; they just do it in different ways. A solution to a problem that uses recursion is called recursive; a solution that uses a loop is called iterative.

The iterative solution is not as elegant as the recursive solution but since an iterative solution does not need to make multiple copies of a function, like the recursive does, is usually faster and always less expensive in terms of memory.

## TM1 go to a wall

Let me try

Please, write the iterative function go_to_wall() that moves Karel to a wall in front of him.

steps = 0

steps = 1

steps = 2

steps = 3

This is easy:

def go_to_wall():
while front_is_clear():   # test the condition
move()                # reduce the problem

# main program
go_to_wall()


## 3rd grade – Pave the way

Work it out

Please, use a while loop to pave the 5 steps in front of Karel’s house.

all done.

## 4th grade – Every steps counts

Work it out

Write an program using while loops that gets Karel to score a touchdown, i.e., have him pick up the first ball he finds and then run to the end zone.

and after

## 5th grade – Strawberries – Reaping what you sow

Work it out

It is summer and the strawberry plants are starting to give fruit. Sweet… have Karel collect all the strawberries on his way home that is somewhere in front of him..

Yummy

## 6th grade – The rooms of doom – In the belly of the sphinx

Work it out

The strategy here is the following. Every cell of the room has a stack of 1 to 6 tokens. Karel has to count the tokens; if the result is..

..an even number (i.e., 2, 4, or 6.), turn right
..an odd number (i.e., 1, 3 or 5), turn left

and move forward by that number to the next stack of tokens.

For example, if Karel finds a stack with 4 tokens he has to turn right and move 4 steps to a cell where he will find the next stack.

This procedure will take us to the home square, in which we will find the star.

Karel starts with an empty bag. We provide you with a function that returns the number tokens of the cell on which Karel is standing.