Write a program that evaluates thefactorials of the integers from 1 to 5.
Question
Write a program that evaluates thefactorials of the integers from 1 to 5.
Solution
Sure, here is a simple program in Python that calculates the factorials of the integers from 1 to 5:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
for i in range(1, 6):
print(f"The factorial of {i} is {factorial(i)}")
Here's how it works:
-
We define a function
factorial(n)that calculates the factorial of a numbern. Ifnis 0, the factorial is 1. Otherwise, the factorial ofnisnmultiplied by the factorial ofn-1. This is a recursive function, meaning it calls itself in its definition. -
We then use a for loop to iterate over the integers from 1 to 5. For each integer
i, we print out the factorial ofiby calling ourfactorial(i)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 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
Write a program to calculate the factorial of N.
Write a C++ Program to find Factorial of a number using classinputEnter a number: 5outputBelow is the input and output of the provided C++ program to find the factorial of a number using a class:Input:Enter a number: 5
Write programs to find (using recursions) 1. Factorial of a number n (This is an example of using recursion) 2. Fibonacci numbers The program demonstrates the concept of Fibonacci numbers. You must convert it into a recursive function 3. Xn 4. Consecutive sum of n numbers 5. Consecutive sum of n odd numbers 6. The sum of the following sequence: 1 2 + 22 + 32 + ... +n2 7. Find GCD of two numbers
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.