0
What is a base case?
Give an example to demonstrate
1 Answer
+ 6
Base case in recursive is the case that is no longer recursive.
For example, Let's take factorial.
In c++,
int factorial(int n){
return n*factorial(n-1);
}
The limited-precision integers would eventually wrap around. In practice, your program might run out of stack space, but some compilers would convert it into a loop using the tail recursion optimization and would actually run until you shut it down.
The Base case will provide a statement that will eventually stop that recursion.
For Factorial Example,
int factorial(int n){
if(n<=1){
return 1;
else{
return n*factorial(n-1);
}
}
}
This code above provides a base case and also ends the recursion.