Recursion
Recursion is a powerful programming concept that involves a function calling itself. In simple terms, a recursive function solves a problem by breaking it down into smaller and simpler subproblems until a base case is reached.
Let's understand recursion through an example. Consider calculating the factorial of a number.
The factorial of a non-negative integer n
is the product of all positive integers less than or equal to n
. It is denoted by n!
.
Here's a C++ code snippet that calculates the factorial of a number using recursion:
1{{ code }}
In the above code, we define a recursive function factorial
that takes an integer num
as input and calculates the factorial. If the input num
is 0, which is the base case, the function returns 1. Otherwise, it multiplies num
with the factorial of num - 1
.
Let's say we want to calculate the factorial of 5. The code calls the factorial
function with input n
equal to 5. The function calculates 5 * factorial(4)
, which further calculates 4 * factorial(3)
, and so on, until it reaches the base case of factorial(0)
, which returns 1. Finally, it returns the result back to the original call, and we get the factorial of 5 as the output.
Recursion is a fundamental concept in programming and is used in various algorithms and data structures. Understanding recursion and its applications will help you solve complex problems more efficiently.
xxxxxxxxxx
using namespace std;
int factorial(int num) {
if (num == 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
int main() {
int n = 5;
int result = factorial(n);
cout << "The factorial of " << n << " is: " << result << endl;
return 0;
}