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) =
5 * 4 * 3 * 2 * 1 = 120$

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

- Using a loop
- Using recursion

Let’s explore both of them.

#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 negativeif(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;}

#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;}

Copyright ©2024 Educative, Inc. All rights reserved

TRENDING TOPICS