Factorial in C

Factorial in C using a for loop


#include<stdio.h>
#include<conio.h>

void main()
{
  int c,n,f=1;

  printf("Enter a number to calculate its factorial\n");
  scanf("%d",&n);
  for(c=1;c<=n;c++)
    f=f*c;

  printf("Factorial of %d = %d\n",n,f);

  getch();
}
Output:-

Factorial program in C using recursion


#include<stdio.h>
#include<conio.h>

long factorial(int);

void main()
{
  int n;
  long f;

  printf("Enter an integer to find its factorial\n");
  scanf("%d",&n);

  if(n<0)
    printf("Factorial of negative integers isn't defined.\n");
  else
  {
    f=factorial(n);
    printf("%d! = %ld\n", n, f);
  }

 getch();
}
long factorial(int n)
{
  if (n == 0)               // Base case
    return 1;
  else
    return (n*factorial(n-1));
}
Output:-

C program to find factorial of a number using Function


#include<stdio.h>
#include<conio.h>
long factorial(int);
void main()
{
  int n;
  printf("Enter a number to calculate its factorial\n");
  scanf("%d",&n);
  printf("%d!=%ld\n",n,factorial(n));
  getch();
}
long factorial(int n)
{
  int c;
  long r=1;
  for (c=1; c<=n; c++)
    r=r*c;
  return r;
}
Output:-


No comments:

Post a Comment