Base case and recursive case
In a recursive function, the base case and recursive case are the two parts that make up the function.
Base Case
The base case is a crucial component of a recursive function. It defines the condition under which the recursion terminates. Without a base case, a recursive function would continue to call itself indefinitely, leading to a stack overflow error. The base case serves as a stopping point, providing a simple solution to the problem when it reaches its smallest or simplest instance.
For example, in a function that calculates the factorial of a number, the base case could be defined as:
Base Case: If n=0n=0 or n=1n=1, return 1
This condition ensures that the recursion halts when it reaches the simplest form of the problem.
Recursive Case
The recursive case describes how the function proceeds with its self-referential calls. It breaks down the problem into smaller instances, gradually approaching the base case. Each recursive call should bring the function closer to the base case, ensuring that the overall problem is eventually solved.
Continuing with the factorial example, the recursive case could be defined as:
Recursive Case: For n>1n>1, return n×factorial(n−1)n×factorial(n−1)
In this case, the function calls itself with a decremented value of nn, moving towards the base case.
Factorial function
function factorial(n) {
// Base case
if (n === 0 || n === 1) {
return 1;
} else {
// Recursive case
return n * factorial(n - 1);
}
}