Recursively find the factorial of a natural number.
- Details
- Category: 12th class computer practical's.
- Published: Friday, 11 June 2021 08:19
- Written by Super User
- Hits: 424
def factorial(n): #function for factorial
if(n==1or n==0):
return 1
result=n*factorial(n-1) # call recursively
return result
#start of program
n=float(input('enter the number for factorial '))
result=factorial(n) #calling function
print('factorial is ',result)
Explanation : In this program we are taking number to find the factorial of a natural number. This is the recursive version of a simple program. Recursion means calling itself again and again. in this program factorial function is calling itself again and again until a condition is met.
We are taking number from keyboard and converting it into float value and storing number value in variable n. result variable is storing value returned by execution of factorial function. factorial function is taking n as parameter or argument. this function will call itself until value of n will become 1 or if the n contains value of 0 or 1 initially.
each time the value of multiplication of n, n-1,n-2,...,2 will store in stack of memory in compiler. when value of argument will become 1 during calling of function then recursion ends and function returns the value stored in result variable of function. this value is then stored in result variable of function and value is printed in next line.