Chapter 59: Swift Nested Loops

1. What is a nested loop? (very clear definition)

A nested loop means one loop inside another loop.

The inner loop runs completely for every single iteration of the outer loop.

Analogy that almost everyone understands:

Think of a calendar:

  • Outer loop = months (12 times)
  • Inner loop = days in that month (28–31 times)

For each month, you go through every day → total iterations = sum of days in each month.

In code terms:

Swift

Total prints: 5 × 3 = 15 times

2. The classic first example – multiplication table

Swift

Output (partial):

text

Why nested loops are natural here:

  • Outer loop = rows (which number we are multiplying)
  • Inner loop = columns (1 × row, 2 × row, 3 × row, …)

3. Real-life example 1 – Tic-tac-toe board (2D grid)

Swift

Output:

text

Key learning points:

  • Outer loop = rows
  • Inner loop = columns inside each row
  • We use two indices: rowIndex and colIndex

4. Real-life example 2 – Seating arrangement / table plan

Swift

Output:

text

Typical pattern:

  • Outer loop = tables / groups / categories
  • Inner loop = people / items / sub-items inside each group

5. Real-life example 3 – Search / filter in 2D data

Swift

Output:

text

6. Real-life example 4 – Pattern printing (great for understanding nesting)

Swift

Output:

text

Reverse pattern:

Swift

Output:

text

7. Very Common Beginner Mistakes & How to Avoid Them

Mistake Wrong / Dangerous code Correct / Better habit Why?
Modifying outer collection inside inner loop for row in grid { for cell in row { grid.append(…) } } Build new collection or use indices Collection mutated while being iterated – crash
Forgetting to reset inner counter for i in 1…5 { for j in 1…5 { print(i,j) } } (but j not reset) Each inner loop is independent Inner loop resets automatically
Using wrong index range for i in 0…rows { … } for i in 0..<rows { … } 0…rows.count tries to access out-of-bounds
Deep nesting (pyramid of doom) 5+ levels of nested for/if Extract to functions or flatten logic Code becomes unreadable & hard to debug
Assuming all rows have same length matrix[row][col] without check if col < matrix[row].count { … } Rows can have different lengths

8. Quick Reference – Most Used Nested Loop Patterns

Goal Typical nested loop structure Real-life feeling / use-case
Print 2D grid / table for row in rows { for col in columns { … } } Chessboard, calendar, spreadsheet view
Process rows & columns independently for row in matrix { for cell in row { … } } Matrix math, image processing, game board
Numbered list inside groups for group in groups { for (i, item) in group.enumerated() { … } } Seating plan, grouped tasks, multi-team leaderboard
Pattern printing (stars, numbers, shapes) for row in 1…n { for col in 1…row { print(“*”) } } Understanding loops, interview questions
Search / filter in 2D data for row in data { for item in row { if condition { … } } } Find all matching cells, count occurrences

9. Small Practice – Try these

  1. Mini multiplication table (5×5) Print 1×1 to 5×5 using nested for
  2. Right-aligned triangle of stars For size = 5, print:
text
  1. Print a 4×6 grid of coordinates Output should look like:
text

Paste your code here if you want feedback or want to see cleaner / more elegant versions!

What would you like to explore next?

  • Nested loops with break and continue
  • Nested loops in SwiftUI (ForEach inside ForEach)
  • How to flatten nested loops into functional style (flatMap, map + joined)
  • Multidimensional arrays + nested loops (2D tables, grids…)
  • Or move to another topic (dictionaries, sets, optionals, switch…)

Just tell me — we’ll continue in the same clear, patient, detailed style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *