son rohan
son rohan

Reputation: 90

Is this a proper use of 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();
    }
  }
}

Upvotes: 4

Views: 193

Answers (5)

Daniel Larsson
Daniel Larsson

Reputation: 6394

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

Upvotes: 7

Arash Saidi
Arash Saidi

Reputation: 2238

That will cause a stack overflow as the recursive call is infinite.

We can define recursion in this way: 1. we start with a method that has a specific state 2. inside this method the method itself is called, but the call changes the state of the method 3. the method has a base case (a case where if a method reaches this state it no longer calls itself recursively).

Upvotes: 0

alex2410
alex2410

Reputation: 10994

Yes, but you must have flag that determine exit from your method, otherwise you catch StackOverFlowError

Upvotes: 0

pamphlet
pamphlet

Reputation: 2104

Yes and no. Technically this is an example of recursion. But this will never terminate. Normally there is some parameter passed into a recursive method so that it can recognize a "base case" which will not recurse.

Upvotes: 0

Quillion
Quillion

Reputation: 6476

This will cause overflow. All recursion should have some kind of base case for exiting so that it does not go infinitely.
Additionally all recursive functions usually receive some kind of an int or some value so that they can use that value in the base case and exit. So for your example I would send int i as an argument into cat and stop when i == 50

Upvotes: 0

Related Questions