We’ve seen that in the body of a for statement, we can place several different statements. Similarly to the for statement, in the
while statement we can also (in addition to other commands) place a new loop statement, and it could be either a while or a for loop. That way, we can build different combinations of inserted loops.
When the two loops are inserted into one another, we call them a double loop, while three nested loops are called a triple loop. Similarly, we can nest any number of loops into one another, we just rarely need a large number of nested loops.
In this lesson we will practice writing combinations of the nested while and for loops.
Various double and multiple loops - tasks¶
Take 4 balls at each square until the end of a row¶
There are one or more squares in front of Karel, and on each of these squares there are four balls (there are no balls on the starting square). Karel needs to pick them all up.
Now, until he reaches the wall, Karel needs to repeat stepping forward and taking 4 balls. Try complementing the program.
Recall, as in the earlier examples of nesting loops, the statement in the body of the inner loop (here it will be the statement
pick_ball()) should be indented further.
Pick up all the balls¶
There is at least one square in front of Karel, and there may be any number of them. On each of the squares in front of Karel there are zero or more balls (the starting square is empty). Karel needs to pick up all the balls.
This task is the generalization of the previous one, so the program that solves this task can be used in the previous one as well. The difference is that now the inner loop must be a while loop, while in the previous task it could have been a for loop as well.
Again, the statement
pick_ball() should be indented further in. This way, it will repeat while the condition of the inner while statement holds, that is, while there is a ball on the square Karel is on at that moment. Taking all the balls, together with the
move statement is repeated in the outer
while loop as long as there are squares in front of Karel. The overall effect of nesting loops is that all the balls from each square will be taken.
Bring all the balls¶
There is a path of unknown length in front of Karel. Karel should collect all the balls from all the squares and bring them to the starting square.
The program has been broken down to smaller pieces by the comments. Add missing statements.
Up and down¶
Karel is on a rectangular board of unknown size (the number of columns is always odd), without any balls on the squares. The goal is for Karel to reach the bottom right square. In order to achieve this, Karel will have to move through the columns alternately up and down.
These are some of the possible looks of the labyrinth:
Spiral to the left¶