A
nested
loop is a loop inside another loop.
To show you an example of a nested
loop, let’s go back to our PE class story. Imagine that your PE teacher has
asked you to do 10 jumping jacks, every time you finish running a lap. You plan
to run 4 laps today.
For the first lap, you start running
and when you finish the lap, you do 10 jumping jacks. For the second lap, you do
the same: run the lap, then do 10 jumping jacks. You will repeat the same
process for each lap till you have finished running all 4 laps and the jumping
jacks associated with each one.
Now, we already know that we can use a Repeat Loop to represent running our laps. We could write it as:
Rpt 4 [
Run one lap around the field
]
We can also see in our above example that
it is possible to write our jumping jacks activity as a Repeat Loop, since it
represents the same action repeated multiple times. We could write it as:
Rpt 10 [
Do one jumping jack
]
Combining these two actions, we can
write the following program for our PE class exercise:
Rpt 4 [
Run one lap around the field
Rpt 10 [
Do one jumping jack
]
]
So there you have your example. Your
“jumping jacks” loop is nested
inside your “laps around the field” loop. You can call the “jumping jacks” loop
the “inner” loop, since it is sitting (or nested) inside another loop (which we
will call the “outer” loop).
Let us look
at another example. Here is a simple piece of code for your Pro-Bot that uses Nested Loops. We will expand the loops to see how it works.
Example:
Rpt 3 [
Rpt 2 [
Fd 5
Rt
]
]
This code has an “outer” Repeat Loop,
consisting of some instructions, that will execute 3 times. “Nested” inside
that loop, there is another Repeat Loop that will execute 2 times. The
instructions “Fd 5, Rt” are within this “inner” loop. Each time that you run
the outer loop, the inner loop will execute twice, as shown in the code below.
Rpt 3 [
Fd 5
Rt
Fd 5
Rt
]
This is how the above program will
look when written without any loops:
Fd 5
Rt
Fd 5
Rt
Fd 5
Rt
Fd 5
Rt
Fd 5
Rt
Fd 5
Rt
The number of times the instructions inside the inner loop executes =
The number of times the outer loop repeats X The number of times the inner loop repeats
The number of times the instructions inside the inner loop executes =
The number of times the outer loop repeats X The number of times the inner loop repeats
In the above example, the number of times the outer loop repeats = 3.
The number of times the inner loop repeats = 2.
So, the total number of times to repeat the instructions within the inner loop = 3 X 2 = 6.
It is also possible to nest more than two loops. That is, you can have a loop inside a loop inside a loop. Or a loop inside a loop inside a loop inside a loop…
No comments:
Post a Comment