Table of Contents
Introduction
A factorial program in C is a very common application of recursion. The factorial of any value can be calculated very easily with the use of recursion.
The factorial of any value says ‘x’ is the product of all natural numbers till x. For example, the factorial of ‘6’ is ‘1*2*3*4*5*6=720’.
A factorial is represented by the symbol ‘!’.
The factorial of 0 and 1 is 1
It is easy to calculate factorial values like 6,10,12 but to multiply 20 natural numbers to find ‘20!’ is quite difficult. So, it’s better to use coding in real-life situations.
Example
#include<stdio.h> int factorial(int f) { if(f==0 || f==1) { return 1; } else { return f*factorial(f-1); } } int main() { int k; printf("Enter a number to find factorial:"); scanf("%d",&k); int fact=factorial(k); printf("Factorial=%d",fact); return 0; }
Output
Explanation
Here, if the integer ‘f’ value is 0 or 1, then return 1; is returning the factorial value as 1. Else the statement return f*factorial(f-1); will multiply ‘f’ with factorial of ‘f-1’ (since f>1). ‘return f*factorial(f-1)’ is calling the function ‘factorial’ inside itself having the argument ‘f-1’.
In the example above, the value of ‘k’ entered by the user is 9.
int fact=factorial(k); This statement calls the ‘factorial’ function by passing 9 in it, and its value will be assigned to a new variable ‘fact’.
Now, let’s see what happens.
In the function definition, the control moves to the ‘else’ part (since, f=9), where execution of the ‘return f*factorial(f-1);’ statement occurs. It will multiply 9 with ‘factorial (9-1)’. And a call to the ‘factorial’ function is made again, but the value passed is 8 this time.
Similarly, this process goes on until the value passed in the ‘factorial’ function reduces to 1.
9*factorial (8)
9*(8*factorial (7))
9*8*(7*factorial (6))
9*8*7*(6*factorial (5))
9*8*7*6*(5*factorial (4))
9*8*7*6*5*(4*factorial (3))
9*8*7*6*5*4*(3*factorial (2))
9*8*7*6*5*4*3*(2*factorial (1))
362,880*factorial (1)
Now, factorial (1) will return 1. Therefore,
Factorial=362,880*1=362,880
In this way, we can find the factorial of any value with such easy steps. The function will call itself until the base condition is satisfied. The whole factorial procedure shown looks complex, and for bigger values, it is even more complex. However, the compiler performs everything in the backend, and we receive our output in a few seconds.
0 Comments