11

Phase 3 - Level 1: Basic Recursion

Chapter 11 • Beginner

75 min

Phase 3 - Level 1: Basic Recursion

Introduction to Recursion

Recursion is a powerful technique where a function calls itself to solve a problem. It's based on the principle of solving a problem by breaking it into smaller, similar subproblems.

Key Concepts

Base Case

The condition that stops the recursion. Without it, recursion would continue infinitely.

Recursive Case

The part where the function calls itself with a modified parameter, moving toward the base case.

Structure of Recursive Function

python.js
def recursive_function(n):
    # Base case
    if n <= some_value:
        return base_value
    
    # Recursive case
    return something + recursive_function(n - 1)

When to Use Recursion

  • Problem can be broken into similar subproblems
  • Each subproblem is smaller than the original
  • Base case is clearly defined
  • Natural recursive structure (trees, sequences)

Common Patterns

  • Print sequences (1 to n, n to 1)
  • Calculate sums and products
  • Generate sequences (Fibonacci)
  • Process digits recursively

Hands-on Examples

Print 1 to N Recursively

def print_1_to_n(n):
    # Base case
    if n == 0:
        return
    
    # Recursive case: print smaller problem first
    print_1_to_n(n - 1)
    print(n)

# Test
n = int(input("Enter n: "))
print_1_to_n(n)

Recursively print 1 to n-1 first, then print n. Base case is when n becomes 0.