+ 2
What is a base case in recursion??
5 Respuestas
+ 5
Hah, we all posted at the same time.
+ 4
It's the case where the recursion stops so it won't go into an infinite recursion loop and cause a stack overflow.
For example the simple factorial function (n*fact(n-1)) has the base case:
if(n <= 1)
return 1;
So when n is equal or less than 1, the function will return 1 and stop recursing.
+ 2
The base case is needed to end the recursive loop. Without it your recursive loop would be infinite and you will eventually run out of stack frames and your program will crash.
It is the most basic end/return value(s) that can be obtained from your algorithm.
Take into account the following:
int fibonacci(int n) {
if (n < 2){
return 1;
} else {
return fibonacci(n-2) + fibonacci(n-1);
}
}
if (n<2) return 1; would be the base case without it recursion is infinite.
+ 2
base case means when to stop
recursion
+ 1
a function is called itself is called resursion. for a programmer very important topic is recursion