13

Phase 3 - Level 3: Pattern Recursion

Chapter 13 • Intermediate

90 min

Phase 3 - Level 3: Pattern Recursion

Introduction

Learn to print patterns using recursive functions. This teaches you how to think recursively about visual output and pattern generation.

Key Concepts

Recursive Pattern Printing

  • Print line of n stars recursively
  • Print square pattern recursively
  • Print triangle patterns (top-down, bottom-up)
  • Print number patterns recursively

Pattern Types

Line Pattern

code
*****

Triangle (Top-Down)

code
*
**
***
****

Triangle (Bottom-Up)

code
****
***
**
*

Square

code
****
****
****
****

Recursive Approach

Print Line of Stars

python.js
def print_stars(n):
    if n == 0:
        return
    print("*", end="")
    print_stars(n - 1)

Print Triangle

python.js
def print_triangle(n):
    if n == 0:
        return
    print_triangle(n - 1)  # Print smaller triangle first
    print_stars(n)  # Print current row
    print()

Problem-Solving Strategy

  1. Base Case: What's the simplest pattern?
  2. Recursive Case: How to build from smaller pattern?
  3. Order Matters: Print before or after recursion?
  4. Helper Functions: Use helper for repeated operations

Common Patterns

  • Increasing Pattern: Recurse first, then print
  • Decreasing Pattern: Print first, then recurse
  • Nested Patterns: Use helper functions
  • Number Patterns: Combine recursion with numbers

Hands-on Examples

Print Line of N Stars Recursively

def print_stars(n):
    # Base case
    if n == 0:
        return
    
    # Print one star and recurse
    print("*", end="")
    print_stars(n - 1)

# Test
n = int(input("Enter n: "))
print_stars(n)
print()  # New line

Base case: 0 stars means nothing to print. Recursive: print one star, then print n-1 stars recursively.