Basic Program #3
3.Read any number and find factorial of a number. (Using Recursion)
#include <stdio.h>
long long int factorial(int n);
int main()
{
int n;
long long int f;
printf("Enter an integer to find it's factorial: ");
scanf("%d", &n);
// show error if the user enters a negative integer
if (n < 0)
{
printf("Error! Factorial of a negative number doesn't exist.\n");
}
else
{
f=factorial(n);
printf("Factorial of %d = %llu\n", n, f);
}
}
long long int factorial(int n)
{
if (n>=1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
long long int factorial(int n);
int main()
{
int n;
long long int f;
printf("Enter an integer to find it's factorial: ");
scanf("%d", &n);
// show error if the user enters a negative integer
if (n < 0)
{
printf("Error! Factorial of a negative number doesn't exist.\n");
}
else
{
f=factorial(n);
printf("Factorial of %d = %llu\n", n, f);
}
}
long long int factorial(int n)
{
if (n>=1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
Output
- Enter an integer to find it's factorial: -1
Error! Factorial of a negative number doesn't exist. - Enter an integer to find it's factorial: 0
Factorial of 0 = 1 - Enter an integer to find it's factorial: 6
Factorial of 6 = 720
Note:
Suppose the user entered 6.Initially, the
factorial()
is called from the main()
function with 6 passed as an argument.Then, 5 is passed to the
factorial()
function from the same function (recursive call). In each recursive call, the value of argument n is decreased by 1.When the value of n is less than 1, there is no recursive call.
Comments
Post a Comment