bornToCode
bornToCode

Reputation: 1

Unable to kill the recursion with return functions

I am in situation where I'm trying to use recursion within a function with double return type. I actually want to display 49 using recursion but it displays 10. I'm not able to understand the mechanism behind this. From what I understood after debugging, the counter function callback itself because of the return values in its backlog and hence goes back to the value 10 instead of just displaying 49. I am not sure of a workaround with this kind of situation. Code describing my problem is presented below:

public static void main(String[] args) {
    int i = 10;
    counter(i);
    System.out.print(i);
}

public static int counter(int i){
    i++;
    if(i < 50)
        counter(i);
    return i;
}

Upvotes: 0

Views: 39

Answers (1)

uoyilmaz
uoyilmaz

Reputation: 3105

You need to assign the returned values to i. You pass the value of i, not a reference to it, so updating it in the method doesn't update i in the scope of the caller.

public static void main( String[] args)
{
    int i = 10;
    i = counter(i);
    System.out.print(i);
}

public static int counter(int i){
    i++;
    if(i < 50)
        i = counter(i);
    return i;
}

Upvotes: 1

Related Questions