Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

How to find the factorial in C language

Sarvech Qadir

The factorial of a number n, represented by n!, is a product of n with all the positive numbers less than or equal to n. For example, factorial(5)=54321=120factorial(5) = 5 * 4 * 3 * 2 * 1 = 120

Let’s see how we can find factorial in C. There are two methods:

  1. Using a loop
  2. Using recursion

Let’s explore both of them.

1. Using a loop

#include <stdio.h>
int main() {
    int n, i;
    // since we are taking, set the start value at 1.
    int factorial = 1;
    // define the value of n for which we have
    // to compute the factorial.
    n = 5;
    // run the loop from 1 to that number, multiplying
    // the previous result with i. 

    // no factorial for negative number, check if number is negative
    if(n<0)
    {
        printf("Factorial does not exist");
        return 1;
    }
    for (i = 1; i <= n; ++i) {
        factorial = factorial * i;
    }
    printf("Factorial of %d = %d", n, factorial);
    return 0;
}

2. Using recursion

#include <stdio.h>

int factorial(int n)
{
  // base case.
  if (n <= 1)
    return 1;
  // recursive case.
  return n * factorial(n-1);

}
int main() {
    int n;
    // define the value of our n for which we have
    // to compute the factorial.
    n = -5;

    if(n<0)
    {
      printf("factorial does not exist");
      return 1;
    }

    // call the factorial(n) function.
    printf("Factorial of %d = %d", n, factorial(n));
    return 0;
}

RELATED TAGS

c

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring