java - Can anyone explain how this code prints 1 to 10? -


can explain how code prints 1 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);     } } 

it's recursive call display method. here argument value passed display method stored in stack. when if condition fails value of n if poped stack , printed line "system.out.println(n)". in other words, every time display method called passing number, number stored in stack when code come out of recursion, use number stack.

doing dry run can see when value 1 passed display method if condition fails , next line prints value 1 2 printed in stack , on print 10 first value passed.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -