SECTION 01 / 17

One loop inside another: nested iteration

1 min read
On this page 1 headings

You already know how to go through a pile once. Now imagine holding one student card, X, while reading several other student cards, Y. Then you pick a new X and repeat the inner scan. That is nested iteration: one repetition runs inside another repetition.

Keep X fixed while Y changes. Only after that inner scan finishes do we move to the next X.
Keep X fixed while Y changes. Only after that inner scan finishes do we move to the next X.

Two passes and two nested loops do different work

PatternWhat happens with 30 cards?Example
Two separate full passes30 + 30 = 60 visitsFind an average, then classify students
Every ordered pair including self30 × 30 = 900 checksA complete 30-by-30 grid
Distinct unordered pairs30 × 29 ÷ 2 = 435 checksCheck each possible student pair once

A visit is not always a pair comparison. A first pass may only place a card in a bin. We will name the work we count so that 30 placements are not silently confused with 30 pair checks.

for each student X:
    for each student Y after X:
        compare X and Y
    # The inner loop finishes before the next X.

For A, B, C, D: X = A compares with B, C, D. Next X = B compares with C, D. Next X = C compares with D. The last card has nobody after it. Three loops nested over n choices can do n × n × n operations; three separate passes do 3 × n visits.

Try it yourself

Do two WHILE statements always mean nested iteration?

Show explained answer

No. Check their position. One WHILE inside the body of another is nested. Two complete loops written one after the other are sequential passes.

Try it yourself

If X is B in the A, B, C, D example, which Y cards remain?

Show explained answer

C and D. A–B was already checked when X was A. B–B is a self-comparison and is excluded.

Try it yourself

With 30 choices in each of three unrestricted nested loops, how many combinations are there?

Show explained answer

30 × 30 × 30 = 27,000. This differs from three sequential scans, which have 90 visits.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑