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.
Question
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.
Solution
Sure, here is a simple program in Python that calculates the factorial of a number using a for loop:
# Get input from user
num = int(input("Enter a positive integer: "))
# Initialize factorial to 1
factorial = 1
# Check if the number is negative, zero or positive
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)
This program first takes an integer input from the user. It then checks if the number is negative, zero or positive. If the number is positive, it calculates the factorial by multiplying all the integers from 1 to the input number using a for loop.
Similar Questions
Write a program to calculate the factorial of N.
c++ program on factorial of a number in short
Write a C program, using functions where the function calculates the factorial of a given integer, and the main() program does I/O and calling of factorial function.
write an iterative code for factorial in c
Write a C++ program to find the factorial of a given integer using recursion.sample input and outputEnter a positive integer: 5 Factorial of 5 is: 120
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.