Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a proper use of recursion?

Tags:

java

recursion

I made what I think is an example of recursion. Is this acceptable? It's not for a project or anything, my professor is just awful so I try to teach myself.

public void theCat() {
  int i;
  for (i = 0; i <= 50; i++) {
    System.out.println(i);
    if (i == 10) {
      theCat();
    }
  }
}
like image 278
son rohan Avatar asked Mar 22 '23 20:03

son rohan


1 Answers

Yes, that is recursion. However, it will be infinite since you never stop it.

What you should do is to have a base case where you check if it is time to stop the recursion. You would also have a reduction step, that will converge the parameter towards the base case, like so:

public int theCat(int i) {
    if (i => 50) 
        return i;
    else
        return theCat(i + 1);
}

To show the effectiveness of this, have a look at a recursive factorial method:

private long factorial(int n) {
    if (n == 1)
        return 1;
    else
        return n * factorial(n-1);
}

Here, the base case checks if we are trying to calculate 1! and in that case returns 1. This is the case where we no longer need to recursively call the method. Instead, we walk backwards along all of the method calls we have made to calculate the final answer:

factorial(5) 
  factorial(4) 
    factorial(3) 
      factorial(2) 
        factorial(1) 
          return 1 
        return 2*1 = 2 
      return 3*2 = 6 
    return 4*6 = 24 
  return 5*24 = 120
like image 76
Daniel Larsson Avatar answered Mar 28 '23 00:03

Daniel Larsson