by BehindJava
Write a program to find Factorial of a number using recursion
In this tutorial we are going to learn about writing a program to find Factorial of a number using recursion.
Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input(“enter the no of terms”))
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Explanation:
- Firstly, create a function called recur_factorial and pass a parameter ‘n’ if it is less than or equal to 1 it returns n else it returns n and multiplies n-1 term with it. Example:
- Assign 5 as n,then it goes to else statement returns 5 and recursion takes place then it takes n as 4 gets into else statement and again recursion takes place and assigns n as 3 and gets into else statement and this process process continues till n is equal to 1.
- we take user input
- if it is less than 0 it prints factorial does not exist for negative numbers, else if number equal to 0 then it prints factorial of 0 equal to 1 else it prints the result.