About Recursion for Newbies in Java
java, recursion, return, static-methods
Solution
Sure, you can write it with just one return:
public static int addNumbers(int value) {
if (value > 1) {
value += addNumbers(value - 1);
}
return value;
}
As you can see, it's done by having some variable retain the running result until you get to the end. In this case I was able to do it in-place in `value`, in other cases you may need to create a local variable, but the idea of storing your intermediate result somewhere until you get to the return point is a general one.
Problem
So, I have this code, which is just the way I solved an exercise that was given to me, which consisted of creating a recursive function that received a number, and then gave you the sum of 1, all the numbers in between, and your number. I know I made it sound confusing, but here's an example: If I inserted the number 5, then the returned value would have to be 15, because: 1+2+3+4+5 = 15. ``` public class Exercise { public static void main(String[] args) { int returnedValue = addNumbers(6); System.out.print(returnedValue); } public static int addNumbers(int value) { if (value == 1) return value; return value = value + addNumbers(value-1); } } ``` Technically speaking, my code works just fine, but I still don't get why Eclipse made me write two returns, that's all I would like to know. Is there a way I could only write "return" once?