A nested loop is just a loop inside the body of another loop.
every iteration of the outer loop, the inner loop runs through all of its iterations
in a nested loop, the inner most loop must finish…
before another iteration of the outer loop is executed
A Simple Case
How many times does the outer loop run? For each run of the outer loop, how many times does the inner loop run? How many times is "You're driving me loopy!" printed out? →
the outer loop runs 5 times
the inner loop runs 10 times
"You're driving me loopy" is printed out 50 times
(between each set of 10 prints, the iteration of the outer loops printed out)
Cheers!
Write a program that asks for how many cheers, and then prints out the appropriate number of cheers.
continually ask for number of cheers
print out that many cheers, each prefixed with the count of the cheer
if the input is zero, stop asking
Some Questions to Ask…
Based on this output… What parts are repeated and what kind of loops would you use for each part? →
asking for input and cheering are repeated
a while loop might make sense for input (the outer loop) and a for loop for cheering (the inner loop)
Some Pseudocode
In pseudocode, how might we describe this program?
A Cheers Implementation
Using the output we've seen, implement the cheers program. →
Password Generator
Below is the output of a program that generates passwords based on a number that is input by the user. It's similar to the cheers example.
Password Generator
Create a program that generates passwords! The passwords only consist of digits, though…
continually ask the user for a number
if the number is 0, stop asking
if the number is not 0, generate a password:
the number entered will specify how many characters are in the password
each character is a randomly generated digit from 0 through 9
for example, if the user enters 4, a password that may be generated is: 3084
Password Generator Solution
Triangle
Draw a triangle made of stars by using nested loops to accumulate single characters. Don't use string multiplication or string formatting. Here's the expected output:
what's the relation between rows and stars?
note that the first row has 1 star, the second has 2 stars, etc.
try accumulating strings into a row using the inner loop
start with an empty string
Potential Solution for Triangle
note that multiplication could have also been a possible implementation
another alternative is to print out each line instead of accumulating strings