Updated: Feb 17
Recursion is the process of defining something in terms of itself. A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will go on to call itself and repeat its actions whereas some condition is met to return a result.
In other words we can say that it is a programming technique in which a function calls itself from its own body definition. It is similar to loop because it repeats the same code a number of times.
Advantages of Recursion
Recursive functions make the code look clean and stylish.
A complex task can be broken down into simpler sub-problems using recursion.
Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
Occasionally the logic behind recursion is hard to follow through.
Recursive calls are costly because they are used a lot of memory and time.
Recursive functions are not easy to debug.
Write a program to input a number and calculate its factorial.
if x == 1:
return (x * fact(x-1))
num=int(input("Enter the Number: "))
print("The factorial of", num, "is", fact(num))
Enter the Number: 3
The factorial of 3 is 6
Write a program to input a number and print its table up to 10 terms.
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
n = int(input("Enter number: "))
Enter number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Python program calculates the sum of the first N Natural numbers using recursive function calls.
return (n + sum(n-1))
num=int(input("Enter a number : "))
print("The sum of natural numbers is ", s)
Enter a number : 4
The sum of natural numbers is 10