Find factorial of an integer

Factorial of an integer n is denoted by n! and determined as the product of all the positive descending integers. Factorial of an integer n is determined by the following equation;

n! = n * (n – 1) * (n – 2) * (n -3) * ……. * 3 * 2 * 1

If you want to determine the factorial of an integer 6, then the result will be as the following;

6! = (6 * 5 * 4 * 3 * 2 * 1) = 720

It should be mentioned that 0! = 1.

In this article we will try to understand and write factorial program in C programming language. We can write a factorial program in different methods. So of the methods of writing factorial program in C are as follows;

  • Factorial program using loop in C
  • Factorial program using function or recursion in C

Now, let’s see some C programs to find out factorial of an integer in C.

Factorial program using loop in C

// factorial program using loop in c
#include <stdio.h>
int main(){
  int number, i, fact = 1;

  printf("Enter the number for calculating its factorial : ");
  scanf("%d", &number);

  for (i = 1; i <= number; i++){   // using loop to calculate factorial
    fact = fact * i;
    }
  printf("\nFactorial of %d is = %d\n", number, fact);

  return 0;
}

Output of this factorial program:

Factorial program using function in C

// factorial program using function or recursion in c
#include<stdio.h>

long fact(int num){   // function to calculate factorial
  if (num == 0){
    return 1;
  }else{
    return (num * fact(num - 1));
  }
}

int main(){
  int num;
  long factorial;

  printf("Enter the integer to find factorial : ");
  scanf("%d", &num);

  if (num < 0){
    printf("Factorial of negative integer is undefined.\n");
  }else{
    factorial = fact(num);
    printf("%d! = %ld\n", num, factorial);
  }
  return 0;
}

Output of this C factorial program

c factorial program, find factorial of integer numbers

Previous pageSum of natural numbers

Next pageFibonacci series