Lesson 9 • Intermediate

Nested Loops

20 minutes
Control Flow

🔄 What are Nested Loops?

Nested loops are loops inside other loops. The inner loop runs completely for each iteration of the outer loop, creating a powerful way to process 2D data, create patterns, and solve complex problems.

Understanding Nested Loops
Think of nested loops like a clock:
  • The outer loop is like the hour hand - it moves slowly
  • The inner loop is like the minute hand - it completes 60 cycles for each hour
For each iteration of the outer loop, the inner loop runs completely!

Visual: How Nested Loops Iterate (3x3 Grid)

Row 1, Col 1
1
Row 1, Col 2
2
Row 1, Col 3
3
Row 2, Col 1
4
Row 2, Col 2
5
Row 2, Col 3
6
Row 3, Col 1
7
Row 3, Col 2
8
Row 3, Col 3
9
Outer Loop (row)
Runs 3 times
Inner Loop (col)
Runs 3 × 3 = 9 total

📐 Basic Nested Loop Structure

For outer = start1 To end1
    # Outer loop code
    
    For inner = start2 To end2
        # Inner loop code (runs many times!)
    Endfor
    
    # More outer loop code
Endfor
Example: Simple Nested Loop
Algorithm SimpleNested

Print "Nested loop demonstration:"
Print ""

For row = 1 To 3
    Print "Outer loop - Row", row
    
    For col = 1 To 3
        Print "  Inner loop - Column", col
    Endfor
    
    Print ""
Endfor

Endalgorithm
Output
Nested loop demonstration: Outer loop - Row 1 Inner loop - Column 1 Inner loop - Column 2 Inner loop - Column 3 Outer loop - Row 2 Inner loop - Column 1 Inner loop - Column 2 Inner loop - Column 3 Outer loop - Row 3 Inner loop - Column 1 Inner loop - Column 2 Inner loop - Column 3

⭐ Pattern Printing

Nested loops are perfect for creating patterns:

Pattern 1: Rectangle

Example: Rectangle Pattern
Algorithm RectanglePattern

var rows = 4
var cols = 6

Print "Rectangle (", rows, "x", cols, "):"
Print ""

For row = 1 To rows
    For col = 1 To cols
        Print "* "
    Endfor
    Print ""  # New line after each row
Endfor

Endalgorithm
Output
Rectangle (4 x 6): * * * * * * * * * * * * * * * * * * * * * * * *

Pattern 2: Right Triangle

Example: Triangle Pattern
Algorithm TrianglePattern

var height = 5

Print "Right Triangle:"
Print ""

For row = 1 To height
    # Inner loop runs 'row' times
    For col = 1 To row
        Print "* "
    Endfor
    Print ""
Endfor

Endalgorithm
Output
Right Triangle: * * * * * * * * * * * * * * *

Pattern 3: Number Pyramid

Example: Number Pyramid
Algorithm NumberPyramid

var height = 5

Print "Number Pyramid:"
Print ""

For row = 1 To height
    # Print row number, repeated 'row' times
    For col = 1 To row
        Print row, " "
    Endfor
    Print ""
Endfor

Endalgorithm
Output
Number Pyramid: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

🔢 Multiplication Table

Example: Full Multiplication Table
Algorithm MultiplicationTable

var size = Input "Enter table size (e.g., 10):"

Print ""
Print "=== Multiplication Table ==="
Print ""

For row = 1 To size
    For col = 1 To size
        var product = row * col
        Print row, "×", col, "=", product
    Endfor
    Print ""  # Blank line between rows
Endfor

Endalgorithm

📊 Working with 2D Data

Nested loops are essential for processing grid/table data:

Example: Temperature Grid
Algorithm TemperatureGrid

Print "=== Weekly Temperature Data ==="
Print ""

# Simulate 7 days, 3 readings per day
var days = 7
var readings = 3
var totalSum = 0
var totalCount = 0

For day = 1 To days
    Print "Day", day, ":"
    var daySum = 0
    
    For reading = 1 To readings
        var temp = Input "  Reading" + reading + ":"
        daySum = daySum + temp
        totalSum = totalSum + temp
        totalCount = totalCount + 1
    Endfor
    
    var dayAverage = daySum / readings
    Print "  Day average:", dayAverage
    Print ""
Endfor

var weekAverage = totalSum / totalCount
Print "=== Weekly Average:", weekAverage, "°C ==="

Endalgorithm

Complex Patterns

Inverted Triangle

Example: Inverted Triangle
Algorithm InvertedTriangle

var height = 5

Print "Inverted Triangle:"
Print ""

For row = height To 1 Step -1
    For col = 1 To row
        Print "* "
    Endfor
    Print ""
Endfor

Endalgorithm
Output
Inverted Triangle: * * * * * * * * * * * * * * *

Diamond Pattern

Example: Diamond Pattern
Algorithm DiamondPattern

var size = 5

Print "Diamond Pattern:"
Print ""

# Upper half (including middle)
For row = 1 To size
    # Print spaces
    For space = 1 To size - row
        Print "  "
    Endfor
    
    # Print stars
    For star = 1 To (2 * row - 1)
        Print "* "
    Endfor
    
    Print ""
Endfor

# Lower half
For row = size - 1 To 1 Step -1
    # Print spaces
    For space = 1 To size - row
        Print "  "
    Endfor
    
    # Print stars
    For star = 1 To (2 * row - 1)
        Print "* "
    Endfor
    
    Print ""
Endfor

Endalgorithm

🎮 Real-World Application

Example: Monthly Calendar
Algorithm SimpleCalendar

var daysInMonth = Input "Enter days in month (28-31):"
var startDay = Input "Starting day of week (1=Mon, 7=Sun):"

Print ""
Print "=== MONTHLY CALENDAR ==="
Print ""
Print " Mon Tue Wed Thu Fri Sat Sun"
Print "-----------------------------"

# Print leading spaces for first week
For i = 1 To startDay - 1
    Print "    "  # 4 spaces per day
Endfor

var currentDay = startDay

For day = 1 To daysInMonth
    # Print day number (padded)
    If day < 10 Then
        Print "  ", day, " "
    Else
        Print " ", day, " "
    Endif
    
    # New line after Sunday
    If currentDay == 7 Then
        Print ""
        currentDay = 1
    Else
        currentDay = currentDay + 1
    Endif
Endfor

Print ""
Print "-----------------------------"

Endalgorithm

Performance Tips

Watch Out for Performance!

Nested loops can get slow quickly! If the outer loop runs N times and inner loop runs M times, the total is N × M iterations.

Example:

  • Outer: 100 iterations
  • Inner: 100 iterations
  • Total: 10,000 iterations!

Be careful with large numbers!

Key Takeaways

  • ✅ Nested loops run an inner loop completely for each outer loop iteration
  • ✅ Perfect for 2D data, grids, and patterns
  • ✅ Total iterations = outer × inner loop counts
  • ✅ Use descriptive variable names (row/col, not i/j)
  • ✅ Can nest any type of loop (FOR, WHILE, REPEAT)
  • ✅ Watch out for performance with large numbers
  • ✅ Great for creating visual patterns and processing tables

💪 Practice Exercises

Try These Exercises

Exercise 1: Hollow Square
Create a hollow square pattern where only the border has stars and the inside is empty.
Exercise 2: Pascal's Triangle
Generate the first N rows of Pascal's Triangle using nested loops and calculations.
Exercise 3: Checkerboard
Create an 8×8 checkerboard pattern alternating between * and # symbols.
Exercise 4: Prime Number Grid
Display numbers 1-100 in a 10×10 grid and mark which ones are prime numbers.
Excellent Work!
You now understand how to use nested loops for complex patterns and 2D data! In the next lesson, we'll learn about functions to create reusable code blocks.