The factorial of a nonnegative integer n is written n! (pronounced \"n r factori
ID: 3813641 • Letter: T
Question
The factorial of a nonnegative integer n is written n! (pronounced "n r factorial") and is defined as follows: n! = n times (n - 1) times (n - 2) times ... times 1 (for values of n greater than or equal to 1) and n! = 1 (for n = 0). For example, 5! = 5 times 4 times 3 times 2 times 1, which is 120. Write a program that reads a nonnegative integer and computes and prints its factorial if the number input is smaller than 3 computes and prints the square of the factorial value for the input number if the input number is larger or equal to 3. For example, if you input 6, the output should be 720*720=51, 840. Show the result for both cases.Explanation / Answer
Program :
#include<stdio.h>
#include<conio.h>
long long int factorial(long long int val); // prototype of factorial function
int main()
{
long long int n , result;
printf("Enter the number"); // Display message to user to enter the number
scanf("%lld",&n); // Store the value in the integer variable
if(n==0)
{
printf("%d",1); // Directly print the value of 0!
}
if(n<3) { //Separate the case of input number whose value is less than 3
printf("%lld",factorial(n));
} else { //Separate the case of input number whose value is more than 3
result = factorial(n);
result = result * result ; // As per the condition sqaure the result if input number is greater than 3
printf("%lld",result);
}
getch();
return 0;
}
long long int factorial(long long int val) // Definition of factorial function
{
long long int fact = 1; // Integer variable to store the result
while(val!=0) // Loop to calculate the result
{
fact = fact * val; // Multiply the input number to result itself
val=val-1; // Decrement the input number until it reaches zero
}
return fact; // return the factorial value.
}
Explanation
1. Here limit of integer is not mentioned so we need to take the integer container which can store maximum value so I have taken long long int.
2. Value of 0! is always zero, so no need to calculate. Directly print 1.
3. We have two conditions two print the output . So I have separated the outputs with if block based on the value of input number n.
4.It is better to write the factorial function separatly. This provides the readability and better understanding.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.