Learn How to Think with Karel the Robot. Chapter 3. Counting Loop

Chapter 3
Counting Loop

In this chapter you will learn:

  • What the counting loop is.
  • How to use the keyword repeat to repeat single commands.
  • How to comment your code, and why commenting your code is important.
  • How to use the repeat loop to repeat sequences of commands.
  • How to quickly and correctly identify a repeating pattern.
  • What to do if a repeating pattern does not start right away.
  • What to do if additional operations are needed after a repeating pattern ends.
  • How to use nested repeat loops.

3.1. Counting loop and the keyword repeat

The concept of counting loop is present in all procedural programming languages such as Python, C/C++, Java, Javascript, Fortran and others. Counting loops allow us to repeat a command, or a sequence of commands, a given number of times. picture

In the Karel language, the counting loop is defined using the keyword repeat. For example, the following code will repeat 10 times the command go:

Program 3.1: Make 10 steps forward!
1repeat 10 
2  go

Notice that the keyword repeat is followed by the number of repetitions (cycles), and that the body of the loop is indented. By body of the loop we mean the command or sequence of commands to be repeated.

Most "real" languages define the counting loop using the keyword for. The Karel language also uses the keyword for, in the same way Python does - this will be explained later. For now let us now look at the following maze:


PIC

Figure 3.1: *

Karel is in the library.


Suppose that the robot needs to collect the book and return to his home square. Here is the algorithm for that:


Algorithm 3.1: *
Collect the book and return to the home square!
1:  Make 10 steps forward.
2:  Collect the book.
3:  Turn around.
4:  Make 11 steps forward.


If we did not have the repeat loop, we would implement the algorithm as shown below. The hash symbol # is used to introduce comments - the rest of the line after this symbol is ignored by the interpreter.

Program 3.2: Implementation without the repeat loop
1# Make 10 steps forward: 
2go 
3go 
4go 
5go 
6go 
7go 
8go 
9go 
10go 
11go 
12# Collect the book: 
13get 
14# Turn around: 
15left 
16left 
17# Make 11 steps forward: 
18go 
19go 
20go 
21go 
22go 
23go 
24go 
25go 
26go 
27go 
28go

However, this program is too long. Let’s make it shorter!

Program 3.3: Program 3.2 rewritten using the repeat loop
1# Make 10 steps forward: 
2repeat 10 
3  go 
4# Collect the book: 
5get 
6# Turn around: 
7repeat 2 
8  left 
9# Make 11 steps forward: 
10repeat 11 
11  go

Again, notice that the command go on lines 3 and 11, as well as the command left on line 8 are indented. This is very important because it makes it clear which commands belong to the body of the loop. picture

3.2. Commenting your code

Good programmers use many comments in their programs. Namely, while writing your program, you know exactly what every line does (at least you should). But when you go do something else, and return to it after several weeks, the program might as well be written by somebody else. Then, the comments will help you to quickly refresh your memory. And of course, comments are absolutely crucial when you work in a team and other team members are using your code. picture

So, the above Program 3.2 has 24 lines, and the shorter Program 3.3 only has 7.

3.3. Repeating a sequence of commands

The body of a loop can contain a sequence of commands, as long as all commands in this sequence are indented. Then the entire sequence is repeated. For illustration, here is a maze with an anchor, chest, and three gold coins:


PIC

Figure 3.2: *

Karel is on a ship.


Karel’s task is to collect the three gold coins, and put them in the chest at the end. This can be done using the following program. Step through it in your mind to make sure it works correctly!

Program 3.4: Collect the gold coins and put them in the chest!
1# Collect the coins: 
2repeat 3 
3  go 
4  get 
5  go 
6  left 
7# Put them in the chest: 
8repeat 3 
9  put

After the program ends, the robot is standing over the chest, facing South:


PIC

Figure 3.3: *

Karel’s position after the program ends.


3.4. Indentation matters

Forgetting one indent can change the outcome of your program completely. For a moment, let’s assume that we committed a syntax error and forgot to indent the command left on line 5:

Program 3.5: Missing indent on line 5
1repeat 3 
2  go 
3  get 
4  go 
5left 
6repeat 3 
7  put

But the forgotten indent means that the command left is no longer part of the loop! This will change everything, and the robot will crash into the wall:


PIC

Figure 3.4: *

One mistake in indentation caused the robot to crash.


The following screenshot shows the corresponding error message, including the line where the error occurred:


PIC

Figure 3.5: *

Error message generated by Program 3.5.


3.5. How to figure out repeating patterns quickly and correctly

Identifying the repeating pattern (the body of the loop) is a fundamental skill of computer programming. Any time spent practicing this skill is time well spent. Let’s look at the following example, where Karel’s task is to collect four coins and enter the home square:


PIC

Figure 3.6: *

Karel needs to collect four coins.


It is clear that there will be four cycles because there are four coins. But what commands should be repeated? The following image helps us to answer this question:


PIC

Figure 3.7: *

First cycle - Karel must collect one coin and get ready in front of the next one.


At the beginning, Karel stands in front of a coin. Therefore, at the end of the first cycle, he must also stand in front of a coin (the next one). And he must have collected one coin on the way. Only then he can repeat the same sequence of commands again. Hence, we have just figured out the body of the loop!

go  
get  
left  
go  
right  
go

When stepping through these six lines for a second time, the robot collects the second coin and moves to the third one:


PIC

Figure 3.8: *

Second cycle.


This is the third cycle - Karel collects the third coin and moves to the last one:


PIC

Figure 3.9: *

Third cycle.


And one last time:


PIC

Figure 3.10: *

Fourth and last cycle.


We already know that there are four cycles, so the first line of the program will be repeat4. After adding the above six lines as the body of this loop, we obtain the final program:

Program 3.6: Collect four coins and enter the home square!
1repeat 4 
2  go 
3  get 
4  left 
5  go 
6  right 
7  go

3.6. Stashing coins

Let’s look at another example where Karel needs to stash four coins in the chests:


PIC

Figure 3.11: *

Stashing coins.


Clearly, there will be four cycles, because there are four coins and four chests. But what commands will form the body of the loop?

Notice that Karel stands with his back to a chest. That must also be his final position after finishing the first cycle - except it will be the next chest which is to his right. And moreover, one coin must be already stashed in this chest. This tells us where Karel needs to go:


PIC

Figure 3.12: *

First cycle.


By now we have figured out the repeating pattern which is formed by the following 10 commands:

right  
go  
right  
go  
go  
get  
left  
go  
put  
go

To verify that these 10 lines are correct, let’s step through them in our mind for a second time:


PIC

Figure 3.13: *

Second cycle.


For a third time:


PIC

Figure 3.14: *

Third cycle.


And finally, one last time:


PIC

Figure 3.15: *

Fourth cycle.


Using the above 10 lines as the body of a repeat loop with four cycles, we obtain the final program:

Program 3.7: Move the four coins to the chests!
1repeat 4 
2  right 
3  go 
4  right 
5  go 
6  go 
7  get 
8  left 
9  go 
10  put 
11  go
picture

3.7. Cooking potatoes

Karel’s next task is to cook some potatoes.


PIC

Figure 3.16: *

Karel must put all potatoes in the pots.


With what you already know, it is easy to see the repeating pattern: At the end of the first cycle, the first potato must be in the first pot and Karel must be ready in front of the second one:


PIC

Figure 3.17: *

Repeating pattern.


Now we know how the body of the repeat loop will look like:

right  
go  
get  
left  
go  
left  
go  
put  
right  
go

Using these 10 lines as the body of a repeat loop with 4 cycles yields the final code:

Program 3.8: Put all potatoes in the pots!
1repeat 5 
2  right 
3  go 
4  get 
5  left 
6  go 
7  left 
8  go 
9  put 
10  right 
11  go

3.8. When it is not be possible to start a loop right away

Sometimes the repeating pattern does not start immediately. For example, consider the last example, but now with Karel standing at a different initial position:


PIC

Figure 3.18: *

Karel’s initial position changed.


This is not a good initial position to start a loop. Therefore, let’s change it! One way to do it is make two steps forward, turn right, make another step forward, and then turn left:

go  
go  
right  
go  
left

Then the robot’s position will match his initial position from the last example, and we will be able to use the previous code:


PIC

Figure 3.19: *

Adjusting Karel’s initial position so that a loop can be started.


Hence, the program to solve the new task will consist of the five commands shown above, followed by Program 3.8:

Program 3.9: Adjust your initial position and put all potatoes in the pots!
1go 
2go 
3right 
4go 
5left 
6repeat 5 
7  right 
8  go 
9  get 
10  left 
11  go 
12  left 
13  go 
14  put 
15  right 
16  get 
17  go

3.9. Additional commands might be needed after a loop finishes

Let’s stay with the last example, but we added a home square where Karel needs to go after putting the potatoes in the pots:


PIC

Figure 3.20: *

Karel moreover needs to enter the home square at the end.


Clearly, we will be able to reuse Program 3.9 but some new commands will have to be added at the end. To figure out what these commands are, we must know where Karel will be after the loop finishes. The best way to find out is to step through the program in your mind. Then you will see that Karel will finish the loop standing on the right of the last pot, looking East:


PIC

Figure 3.21: *

Karel’s position after finishing the loop.


Now it is easy to see that in order to get home, Karel needs to turn right, make two steps, turn right again, and make 12 more steps:

right  
go  
go  
right  
repeat 12  
  go

Hence, here is the final program which consists of Program 3.9 and the above 6 lines:

Program 3.10: Get home after fulfilling the task!
1go 
2go 
3right 
4go 
5left 
6repeat 5 
7  right 
8  go 
9  get 
10  left 
11  go 
12  left 
13  go 
14  put 
15  right 
16  get 
17  go 
18right 
19go 
20go 
21right 
22repeat 12 
23  go

3.10. Nested loops

Sometimes a repeating pattern can contain another repeating pattern. Such as in the following task where Karel needs to collect nine pearls which are grouped into three rows:


PIC

Figure 3.22: *

Karel is on the bottom of the ocean.


These tasks lead to nested loops - loops which contain other loops in their body. Writing programs with nested loops requires practice, so don’t get frustrated or give up when you struggle initially. This is perfectly normal. However, some things can be done to make the solution of these tasks easier.

First, always start from the smaller repeating pattern - in this case, let’s collect the first three pearls first:

repeat 3  
  go  
  get

It is important to step through this loop in your mind, to see where the robot will be after this loop finishes:


PIC

Figure 3.23: *

After finishing the loop.


As you can see, Karel cannot just start the same loop right away (because after making one step forward, there would be no pearl to collect. To get ready for it, he must make one step forward first:


PIC

Figure 3.24: *

After moving one step forward.


Then he can use the same loop as before to collect the next three pearls:

repeat 3  
  go  
  get

When the second loop is finished, he stands where the sixth pearl was:


PIC

Figure 3.25: *

After finishing the second loop.


Again, Karel needs to make one step forward to move in front of the last row of pearls:


PIC

Figure 3.26: *

After moving one step forward.


To collect the last three pearls, the robot can do the same as he already did twice before:

repeat 3  
  go  
  get  
go

At the end, Karel’s position will be:


PIC

Figure 3.27: *

Final position after completing the task.


Hence the final code to solve this task contains the above four lines, repeated three times:

Program 3.11: Collect three rows of pearls!
1repeat 3 
2  repeat 3 
3    go 
4    get 
5  go
picture

3.11. Revisiting previous programs

With the knowledge of nested loops, we can revisit and improve some of our previous programs. Let’s start with Program 3.7 from page 170:

1repeat 4 
2  right 
3  go 
4  right 
5  go 
6  go 
7  get 
8  left 
9  go 
10  put 
11  go

Here, lines 2 and 3 are repeated two times. Therefore, we can use a loop for them:

Program 3.12: Program 3.7 improved using a nested loop
1repeat 4 
2  repeat 2 
3    right 
4    go 
5  go 
6  get 
7  left 
8  go 
9  put 
10  go

Also Program 3.8 from page 178 can be improved in a similar way:

1repeat 5 
2  right 
3  go 
4  get 
5  left 
6  go 
7  left 
8  go 
9  put 
10  right 
11  go

Here, lines 5 and 6 are repeated two times. Therefore we can shorten it using a loop:

Program 3.13: Program 3.8 improved using a nested loop
1repeat 5 
2  right 
3  go 
4  get 
5  repeat 2 
6    left 
7    go 
8  put 
9  right 
10  go

3.12. Crab cake

Today Karel needs to collect three rows of crabs:


PIC

Figure 3.28: *

Karel is collecting crabs.


Each row has length four. To collect the first one, Karel can use the following loop:

repeat 4  
  go  
  get

Then, to get ready in front of the next row, he needs to make a left turn, one step forward, and a right turn:

left  
go  
right

Finally, the solution code for this task will consist of the above two codes put together, and repeated three times:

Program 3.14: Collect three rows of crabs!
1repeat 3 
2  repeat 4 
3    go 
4    get 
5  left 
6  go 
7  right

3.13. Starfish square

This time Karel needs to collect starfish which form a 6×6 square:


PIC

Figure 3.29: *

Karel is collecting starfish.


This task is a bit tricky. Clearly, the square has four sides, and therefore the outer loop will have four cycles. Each side has length six, but in order to create a repeating pattern, Karel will only be collecting five starfish on each side. Think about it for a moment: If he collected six starfish on the first side, then on the next one he would only have five. So he would not be able to collect six as in the first cycle. That would not work!

Moreover, look at Karel’s initial position above. If we wanted to start the inner loop right away, then Karel’s position at its end would have to be as follows:


PIC

Figure 3.30: *

Inoptimal position outside of the square.


This could be done, but the final code would be longer and more complicated than necessary. It is far better to move Karel one step forward to a better starting position as the first thing:


PIC

Figure 3.31: *

Better initial position.


Now, after collecting five starfish and turning left, he is ready for a second cycle of the outer loop! Notice that there is a starfish beneath the robot as it was at the beginning of the first cycle:


PIC

Figure 3.32: *

After collecting the first five starfish and turning left, Karel is ready to repeat.


The following image shows Karel after finishing the nested loops. He stands on the left of the home square and points North:


PIC

Figure 3.33: *

After finishing the nested loops.


Therefore, after the nested loops are finished, he needs to turn right and make one step forward:

right  
go

Here is the final code:

Program 3.15: Collect all the starfish!
1go 
2repeat 4 
3  repeat 5 
4    get 
5    go 
6  left 
7right 
8go
picture

3.14. Triple-nested loops

Some tasks can involve triple-nested repeating patterns. For illustration, let’s take the previous starfish square, but now with three starfish per grid square instead of one. Karel’s task is again to collect all of them:


PIC

Figure 3.34: *

Now there are three starfish per grid square.


The solution program will be very similar to Program 3.15 except that the get command needs to be replaced with a repeat loop with three cycles. As a result, the program will contain a triple-nested loop:

Program 3.16: Collect all the starfish!
1go 
2repeat 4 
3  repeat 5 
4    repeat 3 
5      get 
6    go 
7  left 
8right 
9go

3.15. Pearl necklace

Let’s show one more example of a task that leads to triple-nested loops. This time Karel needs to collect pearls from three boxes:


PIC

Figure 3.35: *

Three boxes of pearls.


With what you already know, it should not be difficult to step through the following program in your mind, and verify that it works correctly:

Program 3.17: Collect three boxes of pearls!
1repeat 3 
2  repeat 2 
3    go 
4    right 
5    repeat 4 
6      go 
7      get 
8    repeat 2 
9      left 
10    repeat 4 
11      go 
12    right 
13  repeat 2 
14    go 
15  left 
16  go 
17  right
picture

3.16. Even more levels of nesting

To show just one example which involves four levels of nested loops, let’s return to our three boxes of pearls. But this time, there will be five pearls per grid square instead of one.


PIC

Figure 3.36: *

Previous task, but with five pearls per grid square.


And this is the corresponding solution program. It was obtained from Program 3.17 by replacing the get command with a repeat loop with five cycles:

Program 3.18: A program with four levels of nested loops
1repeat 3 
2  repeat 2 
3    go 
4    right 
5    repeat 4 
6      go 
7      repeat 5 
8        get 
9    repeat 2 
10      left 
11    repeat 4 
12      go 
13    right 
14  repeat 2 
15    go 
16  left 
17  go 
18  right

3.17. Review questions

Friendly reminder - for every question either none, one, or several answers may be correct.

QUESTION 3.1. Is commenting your code a good practice?

A
Yes, because it helps you understand what you code does.
B
Yes, because it helps others understand what you code does.
C
No, because comments make the code too long.
D
No, because writing comments takes precious time.

QUESTION 3.2. What symbol uses Karel to introduce a comment?

A
%
B
//
C
$
D
#

QUESTION 3.3. What keyword does Karel use for the counting loop?

A
loop
B
repeat
C
cycle
D
while

QUESTION 3.4. What is the body of the counting loop?

A
The number of repetitions.
B
The first command to be repeated.
C
One or more commands which are repeated.
D
The last command to be repeated.

QUESTION 3.5. How is the body of the counting loop defined in Karel?

A
The command(s) are enclosed in square brackets.
B
The command(s) are enclosed in curly braces.
C
The command(s) are written to begin at the beginning of the line.
D
The command(s) are indented.

QUESTION 3.6. Karel is facing North. What direction will he face when the following program finishes?

1repeat 4 
2  go 
3  left

A
West
B
East
C
North
D
South

QUESTION 3.7. Karel is facing North. What direction will he face when the following program finishes?

1repeat 4 
2  go 
3left

A
West
B
East
C
North
D
South

QUESTION 3.8. Karel faces West. Where will he face when the following program finishes?

1repeat 365 
2  left

A
North
B
South
C
East
D
West

QUESTION 3.9. How many steps will Karel make?

1repeat 4 
2  go 
3repeat 2 
4  go

A
6
B
7
C
8
D
9

QUESTION 3.10. How many steps will Karel make now?

1repeat 4 
2  repeat 2 
3    go

A
6
B
7
C
8
D
9

QUESTION 3.11. And finally, how many steps will Karel make with this program?

1repeat 3 
2  repeat 2 
3    repeat 2 
4      go

A
7
B
8
C
12
D
24


Table of Contents

Created on September 27, 2018 in Karel.
Add Comment
0 Comment(s)

Your Comment

By posting your comment, you agree to the privacy policy and terms of service.