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.
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:
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:
Suppose that the robot needs to collect the book and return to his home square. Here is the algorithm for that:
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.
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!
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.
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.
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:
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!
After the program ends, the robot is standing over the chest, facing South:
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:
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:
The following screenshot shows the corresponding error message, including the line where the error occurred:
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:
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:
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!
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:
This is the third cycle - Karel collects the third coin and moves to the last one:
And one last time:
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:
3.6. Stashing coins
Let’s look at another example where Karel needs to stash four coins in the chests:
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:
By now we have figured out the repeating pattern which is formed by the following 10 commands:
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:
For a third time:
And finally, one last time:
Using the above 10 lines as the body of a repeat loop with four cycles, we obtain the final
program:

3.7. Cooking potatoes
Karel’s next task is to cook some potatoes.
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:
Now we know how the body of the repeat loop will look like:
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:
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:
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
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:
Hence, the program to solve the new task will consist of the five commands shown above,
followed by Program 3.8:
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:
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:
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:
go
go
right
repeat 12
go
Hence, here is the final program which consists of Program 3.9 and the above 6 lines:
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:
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:
go
get
It is important to step through this loop in your mind, to see where the robot will be after this loop finishes:
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:
Then he can use the same loop as before to collect the next three pearls:
go
get
When the second loop is finished, he stands where the sixth pearl was:
Again, Karel needs to make one step forward to move in front of the last row of pearls:
To collect the last three pearls, the robot can do the same as he already did twice before:
go
get
go
At the end, Karel’s position will be:
Hence the final code to solve this task contains the above four lines, repeated three
times:

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:
Here, lines 2 and 3 are repeated two times. Therefore, we can use a loop for them:
Also Program 3.8 from page 178 can be improved in a similar way:
Here, lines 5 and 6 are repeated two times. Therefore we can shorten it using a loop:
3.12. Crab cake
Today Karel needs to collect three rows of crabs:
Each row has length four. To collect the first one, Karel can use the following loop:
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:
go
right
Finally, the solution code for this task will consist of the above two codes put together, and
repeated three times:
3.13. Starfish square
This time Karel needs to collect starfish which form a 6×6 square:
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:
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:
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:
The following image shows Karel after finishing the nested loops. He stands on the left of the home square and points North:
Therefore, after the nested loops are finished, he needs to turn right and make one step forward:
go

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

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.
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:
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.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?
- 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?
- A
- West
- B
- East
- C
- North
- D
- South
QUESTION 3.8. Karel faces West. Where will he face when the following program finishes?
- A
- North
- B
- South
- C
- East
- D
- West
Table of Contents
- About
- 1. Introduction
- 2. Basic Commands
- 3. Counting Loop
- 4. Conditions
- 5. Conditional Loop
- 6. Custom Commands
- 7. Variables
- 8. Functions
- 9. Text Strings
- 10. Testing Your Programs
- 11. Boolean Values, Variables, Expressions, and Functions
- 12. Randomness and Probability
- 13. Lists
- 14. Recursion
- 15. Advanced Applications
- Appendix A. Karel App in NCLab
- Appendix B. Self-Paced Karel Course in NCLab