Sushant-user1909920
Sushant-user1909920

Reputation: 11

passing a value to a method and then printing it

i came across this question in an interview.

public class NuVizzDemo {
    public static void main(String args[]){

        int x=6;
        System.out.println("initial value of x is "+x);
        int y=getX(x);
        System.out.println("value of x after method is executed is "+x);
        System.out.println("value of y is "+y);
    }

    private static int getX(int x) {
        // TODO Auto-generated method stub
        if(x==1){
            System.out.println("value of X is "+x);
            return 0;
        }
        else 
            System.out.println("value of x is "+x);
            return 1+getX(x-1);
    }

}

I want to know how come value of y is 1 less than x?

Upvotes: 1

Views: 71

Answers (3)

user1907906
user1907906

Reputation:

Because the function getX is recursive and follows this pattern:

x = 1: 0
x = 2: 1 + getX(1) = 1 + 0 = 1
x = 3: 1 + getX(2) = 1 + 1 + getX(1) = 1 + 1 + 0 = 2
...

Edit: You should make getX more robust by adding a clause for x <= 0. For such a value of x your code will throw a StackOverflowError (which is a Good Thing™ for a question posted on Stack Overflow ☺).

Upvotes: 7

Tanmoy Bhattacharjee
Tanmoy Bhattacharjee

Reputation: 1080

So this recursive call will go for 5 times and at the 5th time the returned value will be 0, because it will return 0 when x == 1.

So when:

x = 1 -> 0
x = 2 -> 0 + 1 = 1
x = 3 -> 1 + 1 + getX(1) = 2
x = 4 -> 1 + 1 + 1 + getX(1) = 3
x = 5 -> 1 + 1 + 1 + 1 + getX(1) = 4
x = 6 -> 1 + 1 + 1 + 1 + 1 + getX(1) = 5

So it's y = 5.

Upvotes: 0

Neeraj Jain
Neeraj Jain

Reputation: 7730

Because

return 1+getX(x-1);

will give you the value 1 + 1 + 1 + 1 + 1 + 0 = 5 since when x reaches to the 1 you are expicitly returning 0.

Upvotes: 1

Related Questions