2017-02-27 4 views
-1

Könnte jemand erklären, wie die Ausgabe des folgenden Code ist 1 2 3 4 5Rekursion in Java (subtrahierend und Druck Zahlen)

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

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

Was das Geheimnis ist? Hast du eine andere Ausgabe erwartet? – shmosel

+2

Ich schreibe Ihnen, weil Sie SO neu sind. Wie @shmosel vorgeschlagen hat, haben Sie nicht angegeben, was Sie erwartet haben, was ein erwarteter Teil einer Frage zu SO wäre. Weißt du, was du tun sollst? Es ist ein notwendiger Teil des Erlernens der Programmierkunst. Folgen Sie, was Ihr Programm Zeile für Zeile macht, verfolgen Sie den Inhalt von Variablen, vorzugsweise auf Papier, und zeigen Sie nacheinander, was gedruckt werden würde. Du solltest schnell deine eigene Antwort sehen. –

+0

Wenn Sie vom Code verwirrt sind, sollten Sie als erstes mit einem Debugger durchgehen. Ich möchte Sie ermutigen, [Wie man kleine Programme debuggen kann] zu lesen (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – EJoshuaS

Antwort

2

Es Rekursion genannt wird.

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

Hier ist, wie es funktioniert (die Einkerbung beachten):

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