Recursion Concepts in Programming

Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem until it reaches a base case.

Key Concepts of Recursion

Example 1: Factorial Calculation

Factorial of a number n (written as n!) is the product of all positive integers up to n.

def factorial(n):
    if n == 0 or n == 1:  # Base case
        return 1
    else:
        return n * factorial(n - 1)  # Recursive case

print(factorial(5))  # Output: 120

Example 2: Fibonacci Sequence

The Fibonacci sequence is defined such that each number is the sum of the two preceding ones, starting from 0 and 1.

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(7))  # Output: 13

How to Understand Recursion?

Advantages and Disadvantages of Recursion