Reputation: 31
Can anyone explain how this code prints 1 to 10???
class demo
{
public static void main(String[] args)
{
display(10);
}
private static void display(int n)
{
if (n > 1)
{
display(n - 1);
}
System.out.println(n);
}
}
Upvotes: 0
Views: 67
Reputation: 211
It's a recursive call to display method. Here the argument value passed to display method is stored in a stack. when the if condition fails then the value of n if poped from stack and printed by line "System.out.println(n)". In other words, Every time display method called by passing a number, the number will be stored in a stack so that when code will come out of recursion, it will use that number from stack.
Doing the dry run you can see when the value 1 is passed to display method the if condition fails and the next line prints the value 1 then 2 will be printed which was in stack and so on it will print up to 10 which is the first value passed.
Upvotes: 2
Reputation: 1
So the main method runs the display method and passes a value of 10. Then, the value is checked to see if it is greater than 1 (which it is). Next. the display method is called again with a value of n-1, which is 9 in this case. Lastly, 10 is printed out.
Now 9 goes through the same cycle. 9 is greater than 1 and display is called with a value of n-1, which is now 8. 9 is printed out and now 8 goes through the display method. This continues to happen until the value is 1 in which case 1 is not greater than 1 and 1 is printed out and the program exits.
This is called a recursive method if you would like to look into it more.
Upvotes: 0