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)
Output:
2) Sum of First N numbers
def sum(n):
if n == 0:
return 0
return n + sum(n - 1)
print(sum(5))
Output:
3) Factorial of a Number
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
4) Print Numbers from 1 to N
def numbers(n):
if n == 0:
return
numbers(n - 1)
print(n)
numbers(5)
Output:
5) Sum of Digits
def digits(n):
if n == 0:
return 0
return (n % 10) + digits(n // 10)
print(digits(123))
Output:
6) Count Digits in a Number
def count(n):
if n == 0:
return 0
return 1 + count(n // 10)
print(count(12345))
Output:
7) Fibonacci Series
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6))
Output:
8) Reverse a String
def reverse(s):
if len(s) == 0:
return s
return reverse(s[1:]) + s[0]
print(reverse("hello"))
Output:








Top comments (0)