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:
Why is the value being decremented in the end, and how do I return the initially calculated value?
It should be like this:
private static int recursionTest(int num){
if (num < 10){
return recursionTest(++num);
}
else
return num;
}
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;
}
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