Recursive function missing out the base condition
suggest changeCalculating the factorial of a number is a classic example of a recursive function.
Missing the Base Condition:
#include <stdio.h>
int factorial(int n)
{
return n * factorial(n - 1);
}
int main(void)
{
printf("Factorial %d = %d\n", 3, factorial(3));
return 0;
}
Typical output: Segmentation fault: 11
The problem with this function is that it recurses with no way to stop. Each call waits on another call, so the program runs until it exhausts the call stack. A typical result is a segmentation fault. It needs a base condition to stop the recursion.
Base Condition Declared:
#include <stdio.h>
int factorial(int n)
{
if (n == 1) /* Base case: stop the recursion. */
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
int main(void)
{
printf("Factorial %d = %d\n", 3, factorial(3));
return 0;
}
Sample output
Factorial 3 = 6
This function returns when n is 1, but only if the initial value of n is at least 1. A call with n less than 1 never hits that test and recurses until the call stack is exhausted. When int is 32 bits, 12! still fits and 13! does not. The overflowing multiplication is signed overflow, which is undefined behavior, not a defined wrap.
Rules to be followed:
- Initialize the algorithm. Recursive programs often need a seed value to start with. This is accomplished either by using a parameter passed to the function or by providing a gateway function that is non-recursive but that sets up the seed values for the recursive calculation.
- Check to see whether the current value(s) being processed match the base case. If so, process and return the value.
- Redefine the answer in terms of a smaller or simpler sub-problem or sub-problems.
- Run the algorithm on the sub-problem.
- Combine the results in the formulation of the answer.
- Return the results.
Source: Recursive Function