-->

Header Ads

Factorial program in c

1.Simple factorial program:

To find factorial we use this formula: n!= 1*2*3*4.....(n-2)*(n-1)*n
#include
#include

void main()
{
clrscr();
long int number,count,fact=1;

  printf("Enter any number to find factorial : " );
  scanf("%ld",&number);

  for(count=1;count<=number;count++)
     {
       fact=fact*count;

     }
  printf("\n factorial of %ld! = %ld ",number,fact);

getch();

}

Output :-


2. Factorial program by using function fact():

Here i am taking one function which name is factorial() to find factorial of given number.to find factorial there result is too large that's why i am taking long return type of function.
#include <stdio.h>
#include<conio.h>
 
long fact(int);
 
int main()
{
  int num;
  long fact = 1;
 
  printf("Enter any number to find factorial\n");
  scanf("%d", &num);
 
  printf("factorial of %d! = %ld\n", num, fact(num));
 getch();
  return 0;
}
 
long fact(int n)
{
  int c;
  long result = 1;
 
  for (c = 1; c <= n; c++)
    result = result * c;
 
  return result;
}

3. Factorial program using recursion:

#include<stdio.h>
#include<conio.h>
 
long fact(int);
 
int main()
{
  int num;
  long f;
 
  printf("Enter any number to find factorial\n");
  scanf("%d", &num); 
 
  if (num < 0)
    printf("Negative integers are not allowed.\n");
  else
  {
    f = fact(num);
    printf("factorial of %d! = %ld\n", num, f);
  }
 getch();
  return 0;
}
 
long fact(int n)
{
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
}

No comments

Powered by Blogger.