You are here

Factorial program in C

Factorials
Factorial program in C using a for loop, using recursion and by creating a function. Factorial is represented by '!', so five factorial is 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 in C using a for loop

#include <stdio.h>
 
int 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);
 
  return 0;
}

Output of C factorial program:
C factorial program output

Download Factorial program.

As n! grows at a faster rate than exponential function 2n, overflow occurs even for two-digit numbers if we use built-in data type. To calculate factorials of such numbers, we need to use data structures such as array or strings.

Factorial program in C using recursion

#include<stdio.h>
 
long factorial(int);
 
int 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);
  }
 
  return 0;
}

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

In recursion, a function calls itself. In the above program, the factorial function is calling itself. To solve a problem using recursion, you must first express its solution in recursive form.

C program to find factorial of a number

#include <stdio.h>

long factorial(int);

int main()
{
  int n;

  printf("Enter a number to calculate its factorial\n");
  scanf("%d", &n);

  printf("%d! = %ld\n", n, factorial(n));

  return 0;
}

long factorial(int n)
{
  int c;
  long r = 1;

  for (c = 1; c <= n; c++)
    r = r * c;

  return r;
}

To calculate the number of permutations, combinations, and to compute the probability, we use factorials.