Java中的递归(减去和打印数字)

时间:2017-02-27 19:50:34

标签: java recursion

有人可以解释以下代码的输出是如何1 2 3 4 5

    mystery6(5); System.out.println();

    static void mystery6(int n)
    {
       if(n==0) return;
       mystery6(n-1);
       System.out.print(n+" ");
    }

2 个答案:

答案 0 :(得分:2)

这叫做递归。

  You call it with 5. 
  It calls itself with 5 -1 or 4.
  It calls itself with 3
  It calls itself with 2
  It calls itself with 1
  It calls itself with 0
  Then it unwinds. It returns to 1
  Prints 1
  Prints 2
  Prints 3
  Prints 4
  Prints 5
  exits.

答案 1 :(得分:2)

这是它的工作原理(记住缩进):

mystery6 is called with 5, 5 != 0 so it calls itself with 4
 mystery6 is called with 4, 4!= 0 so it calls itself with 3
  mystery6 is called with 3, 3 != 0 so it calls itself with 2
   mystery6 is called with 2, 2 != 0 so it calls itself with 1
    mystery6 is called with 1, 1 != 0 so it calls itself with 0
     mystery6 is called with 0, 0 == 0 so it returns
    mystery6 call with 1 is returned, it prints 1
   mystery6 call with 2 is returned, it prints 2
  mystery6 call with 3 is returned, it prints 3
 mystery6 call with 4 is returned, it prints 4
mystery6 call with 5 is returned, it prints 5