NotMyName
NotMyName

Reputation: 692

How should I increment numbers using recursion?

I have a problem with numbers that I want to increment using a recursive function. The function didn't return the value as I was expecting. Upon debugging I saw the numbers being increased but when the value is returned, it appears that the adjustments to the numbers are returned in reverse order.

Here is a simple example:

private static int recursionTest(int num){
    if (num < 10){
        recursionTest(++num);
    }
    return num;
}

public static void main(String[] args) {
    System.out.println(recursionTest(1));
}

The output is always 2. When I'm using the step-through debugger I see the following:

  1. The number increases by 1 with each iteration.
  2. When the number reaches 10 the return statement is executed.
  3. The debugger then highlights the "recursionTest(++num);" line but the number is decreased by 1.
  4. The return statement is executed again.
  5. Steps 3 and 4 is repeated until a value of 2 is finally returned.

Why is the value being decremented in the end, and how do I return the initially calculated value?

Upvotes: 4

Views: 16728

Answers (6)

Varun
Varun

Reputation: 59

private static int recursionTest(int num){
   while(num < 10){
        recursionTest(++num);
        if(num < 10){
            break;
        }
    }
    return num;
}

Above snippet will iterate while loop 10 times only so it will be fast.

Upvotes: -2

harsh
harsh

Reputation: 7692

Try this, use end condition explicitly:

int recursionTest(int num) {
        if(num == 10){ //recursion exit condition
            return num;
        }
        return recursionTest(++num);
    }

Upvotes: 0

Miguel Jim&#233;nez
Miguel Jim&#233;nez

Reputation: 1303

Your problem is that you must return the recursive calling, not the number. If you do so you are going to obtain always your initial value + 1.

Solution:

private static int recursionTest(int num){
    if(num < 10){
        return recursionTest(num + 1);
    }

    return num;
}

Upvotes: 1

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try using this:

num = recursionTest(++num);

Upvotes: 2

ggmathur
ggmathur

Reputation: 843

This is because you're still returning num instead of the result of your recursive function.

private static int recursionTest(int num){
    if (num < 10){
        return recursionTest(++num); 
    }
    return num;
}

Upvotes: 2

Baby
Baby

Reputation: 5092

It should be like this:

private static int recursionTest(int num){
    if (num < 10){
       return recursionTest(++num);
    }
    else
       return num;
}

Upvotes: 12

Related Questions