Program to find Factorial of a Number
Following is the program to find Factorial of a number using
for
loop.#include
#include
void main()
{
int fact,i,n;
fact = 1;
printf("Enter the number\t");
scanf("%d" , &n);
for(i = 1; i {
fact = fact*i;
}
printf("Factorial of %d is %d", n , fact);
getch();
}
Output
Enter the number 5
Factorial of 5 is 120
Program to find Factorial of a Number using Recursion
In this program we will not use for loop, but we will find the factorial using recursion.
#include
#include
int factorial(int n);
void main()
{
int fact, i, n;
printf("Enter the number\t");
scanf("%d", &n);
fact = factorial(n);
printf("Factorial of %d is %d", n, fact);
getch();
}
int factorial(int n)
{
int fact = 1;
if(n==1)
{
return fact;
}
else
{
fact = n * factorial(n-1);
return fact;
}
}
Output
Enter the number 5
Factorial of 5 is 120