Unleashing the Power of Recursion: Calculating the Factorial of a Number
The Factorial: A Mathematical Marvel
The factorial of a positive number n is defined as the product of all positive integers less than or equal to n. For example, the factorial of 6 (denoted as 6!) is 6 × 5 × 4 × 3 × 2 × 1 = 720. On the other hand, the factorial of a negative number doesn’t exist, and the factorial of 0 is 1.
Recursion in Action: Calculating the Factorial
To calculate the factorial of a number using recursion, we can create a user-defined function called multiplyNumbers(). This function takes an integer n as an argument and returns its factorial.
int multiplyNumbers(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * multiplyNumbers(n - 1);
}
}
Let’s walk through an example to illustrate how this works. Suppose the user enters 6. The multiplyNumbers() function is initially called from the main() function with 6 passed as an argument. Then, 5 is passed to multiplyNumbers() from the same function (recursive call). In each recursive call, the value of n is decreased by 1.
The Recursive Process Unfolds
As the recursive calls continue, the value of n decreases until it reaches 1. At this point, there are no more recursive calls, and the factorial is ultimately returned to the main() function.
- In the first recursive call, n is 5, and the function returns 5 × multiplyNumbers(4).
- In the second recursive call, n is 4, and the function returns 4 × multiplyNumbers(3).
- This process continues until n reaches 1.
By leveraging the power of recursion, we can efficiently calculate the factorial of a number. This example demonstrates the elegance and simplicity of recursive functions in C programming.
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Factorial of %d = %d\n", num, multiplyNumbers(num));
return 0;
}