C Program to find factorial

Simple C program to calculate factorial of a number.
#include<stdio.h>
int main()
{
 int n,fact=1;
 printf("Enter a number: ");
 scanf("%d",&n);
 printf("Factorial of %d= ",n);
 while(n>0)
 {
  fact=fact*n;
  n--;
 }
 printf("%d\n",fact);
 return 0;
}
Another C program using for loop
#include<stdio.h>
int main()
{
 int n,fact=1,i;
 printf("Enter a number: ");
 scanf("%d",&n);
 printf("Factorial of %d= ",n);
 for(i=1;i<=n;i++)
 {
  fact=fact*i;
 }
 printf("%d\n",fact);
 return 0;
}
C Program to calculate factorial using recursion
#include<stdio.h>
int CalculateFactorial(int a)
{
 if(a==1)
 return 1;
 else
 return a*CalculateFactorial(a-1);
}
int main()
{
 int n,fact;
 printf("Enter a number: ");
 scanf("%d",&n);
 printf("Factorial of %d= ",n);
 fact=CalculateFactorial(n);
 printf("%d\n",fact);
 return 0;
}


Popular posts from this blog