Karel J Robot - Chapter 5 Programs: Repeating Instructions              BACK TO KAREL MAIN

Instructions that Repeat

We will now learn how to make Karel perform repetitive tasks. In other words, we will learn how to make a command that can cause Karel to perform an action over and over. You will see that this saves many lines of code.

In computer science, the act of repeating a block of code is called a loop. There are two types loops we will use: the for loop and the while loop. See the examples below.

The FOR loop – a loop used when you want a robot to perform the same task a specific number of times.                                                

Example 1: a for loop used to make exactly 5 moves:

public void move()
{
     for(int x=1; x<=5; x++)
     {
          move();
     }   
}

Example 2: a for loop used to make n moves:

public void move(int n)
{
     for(int x=1; x<=n; x++)
     {
          move();
     }   
}

The WHILE loop – a loop used when you want a robot to perform a task repeatedly until a condition becomes false (an unknown number of times).                                          

Example 1: a while loop used to make a robot move to a wall an unknown distance away:

public void moveToWall()
{
     while(frontIsClear())
     {
          move();
     }   
}

Example 2: a while loop used to pick up an unknown number of beepers at its current location:

public void pickAllBeepers()
{
     while(nextToABeeper())
     {
          pickBeeper();
     }   
}