C Program for factorial of a number | GeeksforGeeks

Hello friends and welcome to GeeksforGeeks.
In this video, we’ll see C program for factorial of a number.
Factorial of a non-negative integer n is the multiplication of all positive integers smaller
than or equal to n. i.e. n! is equal to the product
of n, n-1, n-2 and so on up till 1. For e.g., 4! is equal to 4*3*2*1 which is 24. Similarly, 6!
Will be 6*5*4*3*2*1 which is 720. One way to find the factorial of a number
is using recursion. Now, n! can be written as n * (n-1)!. This is so because (n-1)! includes
all the terms from n-1 * n-2 up till 1. Note that 0! and 1! are both 1. To find the factorial of
a number, we call this recursive function factorial. Now, our base case is n=0, which should return
1. For any other n, we return n*factorial(n-1) because as said earlier (n-1)! includes all
terms from n-1 up till 1 multiplied with each other. This is how n! gets calculated using method
of recursion. Now the 2 nd solution we’ll be seeing is
iterative one. Variable res is initially 1 and it will be storing the factorial of the number. Now,
we know that n! is n* n-1*n- 2 and so on till 1. That’s what we are doing here. i goes on
from 2 to n and all the numbers between 2 to n get multiplied and stored in res. This is how
simple the iterative solution is. The time complexity of both the solutions
is O(n). Thank you for watching the video. Please leave
us your comments.

2 thoughts on “C Program for factorial of a number | GeeksforGeeks

Leave a Reply

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