You are here

Factorial program in C

Factorial program in C programming language: Three methods to find factorial, using a for loop, using recursion and by creating a function. 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 a for loop

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int c, n, fact = 1;
  6.  
  7.   printf("Enter a number to calculate its factorial\n");
  8.   scanf("%d", &n);
  9.  
  10.   for (c = 1; c <= n; c++)
  11.     fact = fact * c;
  12.  
  13.   printf("Factorial of %d = %d\n", n, fact);
  14.  
  15.   return 0;
  16. }

Output of C factorial program:
C factorial program output

Download Factorial program.

Factorial program in C using recursion

  1. #include<stdio.h>
  2.  
  3. long factorial(int);
  4.  
  5. int main()
  6. {
  7.   int n;
  8.   long f;
  9.  
  10.   printf("Enter an integer to find its factorial\n");
  11.   scanf("%d", &n);
  12.  
  13.   if (n < 0)
  14.     printf("Factorial of negative integers isn't defined.\n");
  15.   else
  16.   {
  17.     f = factorial(n);
  18.     printf("%d! = %ld\n", n, f);
  19.   }
  20.  
  21.   return 0;
  22. }
  23.  
  24. long factorial(int n)
  25. {
  26.   if (n == 0)
  27.     return 1;
  28.   else
  29.     return(n * factorial(n-1));
  30. }

Recursion is a technique in which a function calls itself, for example, in the above code factorial function is calling itself. To solve a problem using recursion you must first express its solution in recursive form.

Factorial program in C using function

  1. #include <stdio.h>
  2.  
  3. long factorial(int);
  4.  
  5. int main()
  6. {
  7.   int number;
  8.   long fact = 1;
  9.  
  10.   printf("Enter a number to calculate its factorial\n");
  11.   scanf("%d", &number);
  12.  
  13.   printf("%d! = %ld\n", number, factorial(number));
  14.  
  15.   return 0;
  16. }
  17.  
  18. long factorial(int n)
  19. {
  20.   int c;
  21.   long result = 1;
  22.  
  23.   for (c = 1; c <= n; c++)
  24.     result = result * c;
  25.  
  26.   return result;
  27. }