Factorial Program in C

Updated : Jun 21, 2014 in C Programming

Factorial program in C using For Loop and Recursion

In my last post i have explained Fibonacci series in c programming using for loop and recursion. Now i am going to explain about Factorial program in c using for loop and recursion both way, so you will have idea about how same program can be written using different logic.

What is Factorial of a number?
Factorial program in C using recursion

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,

5! = 5x4x3x2x1 = 120

Factorial program in C programming 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 number %d = %d\n", n, fact);
 
  return 0;
}

Factorial program in C programming 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));
}

Please let me know you idea and suggestion in the comment below

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *