2017-02-27 8 views
-1

は、誰かが次のコードの出力は、それが再帰と呼ばれています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+" "); 
    } 
+1

謎は何ですか?別の出力を期待しましたか? – shmosel

+2

あなたには新しいので、私はあなたに書いています。 @shmoselが示唆しているように、あなたはあなたが何を期待しているかを示していません。あなたは何をすべきか知っていますか?それはプログラミングの技術を学ぶために必要な部分です。あなたのプログラムが行ごとに行うことに従い、変数の内容を紙に記録し、印刷されるものを順番に表示します。あなたはすぐにあなた自身の答えを見なければなりません。 –

+0

コードが混乱している場合は、デバッガを使って最初に試してみてください。私は[小さなプログラムをデバッグする方法](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を読むことをお勧めします。 – EJoshuaS

答えて

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. 
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 
関連する問題