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
- Base Case: What's the simplest pattern?
- Recursive Case: How to build from smaller pattern?
- Order Matters: Print before or after recursion?
- 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 lineBase case: 0 stars means nothing to print. Recursive: print one star, then print n-1 stars recursively.
Related Tutorials
🔗Related Content
- 💻
Phase 3 - Practice Problems
Practice Phase 3 concepts with hands-on coding problems
- 📝
Phase 3 - Quiz
Test your Phase 3 understanding with assessment questions
- ➡️
Phase 4 - Get Started
Continue to Phase 4 after mastering Phase 3
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum