I'm teaching myself about recursive calling of methods in java. I'm constantly getting StackOverFlowErroron my implementation:
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
}
}
i have set the limit to 42 in the main. Can someone point me to the right direction on this? Its supposed to terminate once limit == 0
This doesn't finish the recursion, since you don't exit the method when the condition is met, and you still make the next recursive call (m(limit - 1);) :
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
This will end the recursion :
if (limit == 0) {
System.out.println("finished2");
return;
}
m(limit - 1);
The correct recursion can be :
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
} else {
m(limit - 1);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With