One loop inside another: nested iteration
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.

Two passes and two nested loops do different work
| Pattern | What happens with 30 cards? | Example |
|---|---|---|
| Two separate full passes | 30 + 30 = 60 visits | Find an average, then classify students |
| Every ordered pair including self | 30 × 30 = 900 checks | A complete 30-by-30 grid |
| Distinct unordered pairs | 30 × 29 ÷ 2 = 435 checks | Check 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.
