0
Recursion
Please explain how it work? http://www.sololearn.com/app/java/playground/c4NJ2Nr8h51B/
2 Respuestas
0
import java.util.LinkedList;
public class MyClass {
    public static void main(String[ ] args) {
           
           printNum(5);
        }
        
       public static void printNum(int n){
           if(n==1) {
              System.out.println(n); 
           }else{
               printNum (n-1);
              System.out.println(n);
              
           
           }
}
}
This application starts with printNum with value 5. Let's  trace the function.
there is a condition statement.
If 5==1  False
Else //here
in else bracket, printNum (4) is called.
Then let's start printNum with value 4.
if 4==1 False
Else //Again here.
...
then you'll  reach at printNum (1).
If 1==1 True
Yeah!
then program prints out 1. (value of n)
then this function ends.
In printNum (2),
     Else
          printNum (1) was done.
          So next statement works.
This prints out 2 (value of n)
Again, this function of printNum (2) finishes, system reads next line of printNum (3), which called printNum (2) in Else.
...
Therefore the result is
1
2
3
4
5
0
Thanks @kimminkwan



