Factorial of a number
Aim: Implement
a program to find the factorial of a number provided by the user.
Algorithm:
1:Start
2:Declare variables n,factorial and i.
3:Initialize
variables factorial←1,i←1
4:Read
value of n
5:Repeat
the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
6:Display
factorial
7:Stop
Program:
# take input from the
user
num =
int(input("Enter a number: "))
factorial = 1
# check if the number
is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist
for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial
of",num,"is",factorial)
Output :
Enter
a number: -2
Sorry,
factorial does not exist for negative numbers
0 Comments:
Post a Comment