b1694621
b1694621

Reputation: 3

Can anyone explain how does the following recursion work?

I have some trouble understanding the following recursive code:

public class recursive {
    public static void main(String[] args){ 
        helper(0) ;
    }

    public static void helper(int i){
        int a=3;
        if(i==a){
            System.out.println("yes:"+i);
            return;
        }else{
            for(;i<a;i++){ 
                System.out.println("no:"+i);
                helper(i+1);
                System.out.println("end:"+i);
            }
        }
    }         
}

The Output is as follows:

no:0
no:1
no:2
yes:3
end:2 //why this is 2?
end:1 //why this is 1?
no:2
yes:3
end:2
end:0
no:1
no:2
yes:3
end:2
end:1
no:2
yes:3
end:2

I do not understand why the first end is 2. Can anyone explain how does the recursion work in this simple program?

Upvotes: 0

Views: 56

Answers (2)

Eran
Eran

Reputation: 393781

Each call to helper has its own local value of i.

So when i==2, and you call helper(i+1), the next call to helper has i==3, but when it returns, it goes back to the previous helper invocation, for which i==2.

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44834

try

public static void helper(int i){
    int a=3;
    if(i==a){
        System.out.println("yes:"+i);
        return;
    }else{
        System.out.println("no:"+i);
        helper(i+1);
    }
}  

one idea of recursion is to do away with loops

Upvotes: 1

Related Questions