DEV Community

Sasireka
Sasireka

Posted on

Recursion Programs

What is Recursion?

  • Recursion is a programming technique where a function calls itself to solve a problem.

  • Instead of using loops (for, while), recursion breaks a problem into smaller parts of the same problem.

  • Here are 8 simple recursion programs:

1) 1 2 3 4 5

def display(num):
    if num <= 5:
        print(num, end=" ")   
        display(num + 1)

display(1)

Enter fullscreen mode Exit fullscreen mode

Output:

2) Sum of First N numbers

def sum(n):
    if n == 0:
        return 0
    return n + sum(n - 1)

print(sum(5))
Enter fullscreen mode Exit fullscreen mode

Output:

3) Factorial of a Number

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

Output:

4) Print Numbers from 1 to N

def numbers(n):
    if n == 0:
        return
    numbers(n - 1)
    print(n)

numbers(5)
Enter fullscreen mode Exit fullscreen mode

Output:

5) Sum of Digits

def digits(n):
    if n == 0:
        return 0
    return (n % 10) + digits(n // 10)

print(digits(123))

Enter fullscreen mode Exit fullscreen mode

Output:

6) Count Digits in a Number

def count(n):
    if n == 0:
        return 0
    return 1 + count(n // 10)

print(count(12345))
Enter fullscreen mode Exit fullscreen mode

Output:

7) Fibonacci Series

def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6))
Enter fullscreen mode Exit fullscreen mode

Output:

8) Reverse a String

def reverse(s):
    if len(s) == 0:
        return s
    return reverse(s[1:]) + s[0]

print(reverse("hello"))
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)