4.4 Nested Iteration
Earlier in this unit, you saw how to use a loop for a repeated task. For example, if you wanted to print the numbers 1 through 5 on a line, you could use a loop like this:
What if you wanted to print something like this?
You could use 5 loops, one for each line and each loop starting and stopping at different values. This would get repetitive and you saw how you could use loops to avoid repetitive code. In this section, you are going to explore the concept of a nested loop.
Just as you saw with if statements, putting a loop inside another loop is called nesting. A nested iteration statement is an iteration statement that appears in the body of another iteration statement.
In the example above, you can achieve the five-by-five print out using a nested for
loop.
The original loop is now wrapped inside of a second loop. Watch how the execution plays out.
Each time through the outer loop, the inside loop starts over and runs to completion. After completing the inside loop and printing a row, a line feed is added, then the outer loop loops around and starts the next row.
In this example, the inner loop executes 5 times each time it is called. The outer loop also executes 5 times, each time creating a new inner loop. So each line of code inside the inner loop actually executes 25 times!
Just as there are nested for
loops, you can also have nested while
loops, or even mixed nested loops with a for
loop inside a while
loop, or vice versa.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
How often is the inner loop of a nested loop run?
In this program, you need to make an addition table. Your output should look like:
Modify the makeAdditionTable()
method in the starter code to create this!
Hint: To evenly space these, you may want to use \t
.