UPI Study › Courses › C++ Programming › Free lessons › Lesson 5.5 Free with a free account
Nested Iteration
C++ Programming · Chapter 5: IterationSection 5.5 · lesson 33 of 84video coming soon
← The do-while LoopNext lesson: break, continue, and Other Flow Controls →
In this lesson
Placing loops inside loops for multi-layered problems.
- Count exactly how often an inner body runs
- Explain why the inner counter restarts
- Print rectangles and triangles, with the break in place
- Lay out tables as rows and cells
Transcript
Everything said in the video, section by section (1,252 words). Read along, or search it.
Opening Idea
When Loops Multiply Instead of Add
A loop repeats a body. When that body is itself a loop, one pass of the outer repetition contains an entire run of the inner one. And the work no longer adds up. It multiplies. This is the shape behind every grid, table, calendar, and printed pattern. And it's the first construct where a small change to a bound can have a very large effect.
Core Rule
Inner Loop Finishes Before Outer Advances
There's a single rule, and everything else follows from it. For each pass of the outer loop, the inner loop runs all the way through, from its start to its finish. The outer loop doesn't advance until the inner one has completely finished. Here, i is 1, and j runs 1, then 2. Then i becomes 2, and j starts over: 1, then 2. Then i is 3, and j runs 1, 2 once more. The first number changes slowly, and the second changes quickly. That's always the signature of nesting, like the hands of a clock. The restart is the part that surprises people. The inner loop's initialization is part of the inner loop, so it runs again every time the inner loop is entered.
Counting Passes
Bounds Multiply into Large Totals
With independent bounds, the number of times the innermost body runs is simply the product. Four outer passes of six inner passes is 24. Twelve months of up to 31 days is 372. A thousand by a thousand is a million, from two innocent-looking bounds. The last loop counts something else, and we'll come to it. Nothing about the code looks a thousand times bigger. Doubling one bound doubles the total. But doubling both quadruples it, so the cost of a nested loop grows far faster than the numbers in it suggest.
Quick Check
Doubling Both Bounds of Five by Eight
Pause and predict. An outer loop makes 5 passes, and an inner loop makes 8. Now double both bounds. How many times does the inner body run? One hundred sixty: ten times sixteen. That's four times the original forty, because doubling both bounds quadruples the work.
Optimization
Lifting Outer-Only Work Out of the Inner Loop
The second consequence: anything placed in the innermost body pays that multiplied price. Suppose a value called base depends only on i. Computed inside the inner loop, it runs a million times, and 999,000 of those calculations are wasted. Lifted into the outer body, it runs a thousand times. Moving one line up a level removes all the waste, and the results are identical.
Grid Pattern
Rows Outside, Columns Inside
The most direct use of nesting is anything laid out as a grid. The mapping is always the same. The outer loop counts rows, and the inner loop counts positions within one row. Here, four rows, and in each row, six columns, printing a star at each position. After the inner loop finishes, still inside the outer body, the program prints a line break. The result: four rows of six stars.
Common Mistake
Line Break Inside the Inner Loop
The line break is the part to get right, and its position isn't a matter of taste. Here is a smaller grid, 2 rows of 3, so the results fit on screen. Put the break inside the inner loop, and a break follows every star: one tall column.
Common Mistake
Line Break After the Outer Loop
Put it after the outer loop, and you get one long line of 6 stars. Every star is printed before the only break arrives.
Correct Placement
One Break per Completed Row
After the inner loop, inside the outer body, gives the intended grid: one break per completed row, which is one per outer pass. It belongs there because that's exactly the moment one row has been completed, and the next hasn't yet begun.
Dependent Bounds
Inner Bound Tied to the Outer Variable
Nothing requires the inner bound to be a fixed number. It can be an expression involving the outer variable. The moment it is, each outer pass runs a different number of inner passes. Change the inner condition to column at most row, and each row is one longer than the last. That's a triangle. 1 plus 2 plus 3 plus 4 plus 5: 15 inner passes, against 25 for a square. Swap one fixed bound for the outer variable, and both the shape and the work change.
Cost Analysis
Triangular Totals Still Grow Quadratically
The total for a triangular loop is 1 plus 2, and so on up to n. That comes to n times n plus 1, over 2. It's a little over half of n squared. For 5 rows, 15 rather than 25. For 1,000 rows, 500,500 rather than a million. The saving is real, but it isn't a change of scale. A triangular loop still grows in proportion to the square of its bound.
Variation
Flipping the Triangle Upside Down
Start the inner loop from the outer variable, instead of ending it there, and the triangle turns upside down: five stars, then four, down to one.
Worked Example
Multiplication Table with Aligned Columns
A table is a grid with values in it rather than characters, and it's written with exactly the same shape. The outer loop decides what a row is. The inner loop decides what a single cell is. Here, each cell prints row times column. Only one expression changed from the star pattern. And s t d set w reserves a fixed width for each value, so the columns line up, however many digits a number has. The structure didn't change at all. Once you can see a problem as rows of cells, the loop writes itself.
Choosing Levels
Deciding Which Variable Goes Outside
The same skeleton produces a report. Saying one sentence out loud before writing the code settles which variable belongs where. A star rectangle: rows outside, positions inside. A multiplication table: the first factor outside, the second inside. A quarterly report: departments outside, one per line, and quarters inside. And a calendar year: months outside, days inside.
Good Habits
Keeping Nested Loops Manageable
A few habits keep nesting manageable. Use different variables at each level. Reuse one for both loops, and the inner loop destroys the outer loop's position. Here, the inner loop reuses i. It counts three cells and leaves i at 3, so the outer update makes it 4 and the test fails. Three cells, not nine. Choose names that say what the level is: row and column, or month and day. Never change the outer counter from inside. And keep one indentation level per depth. And stop at two levels where you can. A third level is usually a signal that part of the work should be described separately.
Self Check
What Does One Outer Pass Accomplish?
When you've written a nested loop, answer one question out loud. What does a single pass of the outer loop accomplish? It prints one complete row. It produces one department's line of figures. If the answer comes easily, the structure is right. If you find yourself describing single cells, the levels have been mixed up. Something that belongs to a whole row is running once per cell.
Key Terms
Vocabulary of Nested Loops
A few key terms. A nested loop is a loop written inside the body of another loop. The inner loop restarts from its initialization on every outer pass. Independent bounds don't involve the outer variable: a rectangle, and a product. Dependent bounds do: a triangle, and a smaller total. And the innermost body is the deepest level, the statements that run the multiplied number of times.
Key Takeaways
Summary and a Five Hundred Challenge
To summarize. The inner loop runs completely for every pass of the outer loop, and its counter restarts each time. Totals multiply, so lift anything that depends only on the outer variable out of the inner body. The line break goes after the inner loop, inside the outer body. Dependent bounds give triangles. Check your structure by saying what one outer pass accomplishes. Here's something to think about. With bounds of 500 and 500, an expression depends only on the outer variable. How many calculations does lifting it out of the inner body save?
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Nested Iteration
How do you count how many times the inner body of a nested loop runs?
Why does the inner loop counter start over on every pass of the outer loop?
How do you print a rectangle or triangle with nested loops, and where does the line break go?
How do you print a multiplication table with aligned columns in C++?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →