Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Recursive Method how does it work?

Tags:

java

recursion

I'm relatively new to Java programming and I've just started learning recursion, but I can't seem to figure out how this method works in my head.

   private static int mystery(int w) {
    {
        if (w < 0) return 0;
        int x = mystery (w-2);
        return w - x;
    }
}

Whenever a variable like 100 is put in, it outputs 50. When 200 is input, it outputs 100. When 2 is input, it outputs 2. When 25 is input, 13 is output. I'm not sure how this method works, and I'm trying to wrap my head around it.

The way I currently view it, if you put in 100, it'll bypass the first return statement since it is greater than 0. when it gets to the second line, it'll do 100-2, which brings in 98, then goes to the third line and does 100 - 98 = 2. Which is then returned to the original call.

I know I'm messing up on the second line of the method where the mystery (w-2) is. I assume it would bring back the result of w-2 to the beginning of the method again, and it would continue to do the method over and over again until w is smaller than 0, which should output 0 again regardless of the answer. But that's not what happens, and I don't know why.

Can anyone explain what is going on here?

like image 928
DanG Avatar asked Dec 06 '25 02:12

DanG


1 Answers

What you are missing is that on the second line it doesn't just do w - 2, but calls itself with w - 2. It doesn't go further until the call returns. And the second call calls itself if w isn't < 0 and so on until you reach value lower than 0 and then return. The execution will go like this, if you visualize it:

mystery(10)
    > skip first line
    > x = mystery(8)
        > skip first line
        > x = mystery(6)
            > skip first line
            > x = mystery(4)
                > skip first line
                > x = mystery(2)
                    > skip first line
                    > x = mystery(0)
                        > skip first line
                        > x = mystery(-2)
                            > return 0
                        > return 0 - 0 (0)
                    > return 2 - 0 (2)
                > return 4 - 2 (2)
            > return 6 - 2 (4)
        > return 8 - 4 (4)
    > return 10 - 4 (6)

With example of w = 10. I hope you understand it better now.

like image 60
Franko Leon Tokalić Avatar answered Dec 08 '25 16:12

Franko Leon Tokalić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!