Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion with termination condition Java

Tags:

java

recursion

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

like image 821
Antoine089 Avatar asked Jan 24 '26 22:01

Antoine089


2 Answers

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);
like image 199
Eran Avatar answered Jan 26 '26 11:01

Eran


The correct recursion can be :

    public class LimitedRecursion {
public void m(int limit) {
    if (limit == 0) {
        System.out.println("finished2");
    } else {
        m(limit - 1);
    }
}

}

like image 41
Ansu Avatar answered Jan 26 '26 12:01

Ansu