Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion inside while loop, How does it work?

Can you please tell me how does this java code work? :

public class Main {
    public static void main (String[] args)  {
        Strangemethod(5);
    }
    public static void Strangemethod(int len) {
        while(len > 1){
            System.out.println(len-1);
            Strangemethod(len - 1);
        }
}
}

I tried to debug it and follow the code step by step but I didn't understand it.

update: sorry I didn't mention that I know the result of this code but just want to know the steps of the execution..

like image 302
Mohamad Alhamoud Avatar asked Jun 18 '10 14:06

Mohamad Alhamoud


1 Answers

That'll print 4 3 2 1 1 1 1 1 1...

And get stuck in a loop because nothing ever modifies len in the scope of the while loop. The first calls (with len=5, 4, then 3) go through one loop iteration, and are left waiting for Strangemethod to return. When when len=2, the while loop calls strangemethod(1), and since len is not greater than 1, the while loop finishes and that call returns. But len is still 2 in the bottom-most remaining whle loop, so it calls strangemethod(2) again. And again. And again.

if() would've been more appropriate than while().

like image 94
dannysauer Avatar answered Sep 20 '22 02:09

dannysauer