Factorial program in c

Factorial program in c: c code to find and print factorial of a number, three methods are given, first one uses for loop, second uses a function to find factorial and third using recursion. Factorial is represented using '!', so five factorial will be written as (5!), n factorial as (n!). Also
n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.

Factorial program in c using for loop

Here we find factorial using for loop.
#include <stdio.h>
 
int main()
{
  int c, n, fact = 1;
 
  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &n);
 
  for (c = 1; c <= n; c++)
    fact = fact * c;
 
  printf("Factorial of %d = %d\n", n, fact);
 
  return 0;
}

Output of code:

factorial code output

Factorial program in c using function

#include <stdio.h>
 
long factorial(int);
 
int main()
{
  int number;
  long fact = 1;
 
  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &number);
 
  printf("%d! = %ld\n", number, factorial(number));
 
  return 0;
}
 
long factorial(int n)
{
  int c;
  long result = 1;
 
  for (c = 1; c <= n; c++)
    result = result * c;
 
  return result;
}

Factorial program in c using recursion

#include<stdio.h>
 
long factorial(int);
 
int main()
{
  int n;
  long f;
 
  printf("Enter an integer to find factorial\n");
  scanf("%d", &n); 
 
  if (n < 0)
    printf("Negative integers are not allowed.\n");
  else
  {
    f = factorial(n);
    printf("%d! = %ld\n", n, f);
  }
 
  return 0;
}
 
long factorial(int n)
{
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
}
Recursion is a technique in which a function calls itself, for example in above code factorial function is calling itself. To solve a problem using recursion you must first express its solution in recursive form.

No comments:

Post a Comment