Write a program to calculate the factorial of N.
Question
Write a program to calculate the factorial of N.
Solution
Sure, here is a simple program in Python that calculates the factorial of a number N:
def factorial(N):
if N == 0:
return 1
else:
return N * factorial(N-1)
N = int(input("Enter a number: "))
print("The factorial of", N, "is", factorial(N))
Here's how it works:
-
The function
factorial(N)is defined. This function will calculate the factorial of the numberN. -
Inside the function, there is a condition that checks if
Nis equal to 0. If it is, the function returns 1. This is because the factorial of 0 is 1. -
If
Nis not 0, the function returnsNmultiplied by the factorial ofN-1. This is a recursive call, meaning the function calls itself with a different argument. -
Outside the function, the program asks the user to enter a number and assigns it to
N. -
Finally, the program prints the factorial of
Nby calling thefactorial(N)function.
Similar Questions
Write a program that takes a positive integer as input and calculates its factorial using a for loop. The factorial of a number is the product of all positive integers up to that number.
Write a python function to find the factorial of given number
c++ program on factorial of a number in short
Write a Shell script to find Factorial of a given number.
Python Program to Find the Factorial of a Number Without Recursion
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.