Theoretical recap.
A loop repeats a block of instructions until a condition is met.
You have already worked with while loops, repeat as long as a condition is true; and for loops, repeat a known number of times with a counter.
The mental model to keep in mind, a loop has three parts, an initialization, starting value of the counter, a condition, when to stop, and an increment, how the counter changes each turn.
For example, a for loop counting from one to five initializes a counter at one, continues while the counter is less than or equal to five, and adds one at each iteration.
A nested loop is a loop placed inside another loop.
The inner loop runs entirely for each single iteration of the outer loop.
If the outer loop runs three times and the inner loop four times, the inner block executes three times four equals twelve times.
This is exactly the structure needed to build a two-dimensional grid, such as a multiplication table.
Common mistakes, confusing the two counters, using the wrong variable in the calculation, off by one errors, starting at zero instead of one or stopping one step too early, and forgetting to reset or correctly place the inner loop so it restarts on each outer pass.
Mini example.
For i from one to three, for j from one to three, print i times j.
This produces one comma two comma three, then two comma four comma six, then three comma six comma nine, a small multiplication grid.
Read the full transcript.
Create an account to read the whole episode, search across every transcript, and follow the shows you care about.
Theoretical recap.
A loop repeats a block of instructions until a condition is met.
You have already worked with while loops, repeat as long as a condition is true; and for loops, repeat a known number of times with a counter.
The mental model to keep in mind, a loop has three parts, an initialization, starting value of the counter, a condition, when to stop, and an increment, how the counter changes each turn.
For example, a for loop counting from one to five initializes a counter at one, continues while the counter is less than or equal to five, and adds one at each iteration.
A nested loop is a loop placed inside another loop.
The inner loop runs entirely for each single iteration of the outer loop.
If the outer loop runs three times and the inner loop four times, the inner block executes three times four equals twelve times.
This is exactly the structure needed to build a two-dimensional grid, such as a multiplication table.
Common mistakes, confusing the two counters, using the wrong variable in the calculation, off by one errors, starting at zero instead of one or stopping one step too early, and forgetting to reset or correctly place the inner loop so it restarts on each outer pass.
Mini example.
For i from one to three, for j from one to three, print i times j.
This produces one comma two comma three, then two comma four comma six, then three comma six comma nine, a small multiplication grid.