Bifalgorithm post · Computer science one · Recursion

How can a countdown be written without a loop?

How can a countdown be written without a loop? (Computer science one · Recursion) — "Suppose we wanted to write a simple program that performed a countdown, pr…

Ideas in this flowchart

  • Rekursiver Countdown ohne Schleifen
  • Das Programm soll die Zahlen n bis 0 ausgeben und bei null „Happy New Year!!!“ anzeigen.
  • Naheliegend wäre zunächst eine for-Schleife mit einer Zählvariable.
  • In der angenommenen Umgebung stehen jedoch keine gewöhnlichen Schleifenstrukturen zur Verfügung.
  • Stattdessen wird der Countdown durch rekursive Funktionsaufrufe umgesetzt.
  • Eine Funktion erhält den aktuellen Zählerwert, verringert ihn und ruft sich anschließend selbst auf.
  • Die Funktion CountDown erhält eine ganze Zahl n ≥ 0 und erzeugt die Ausgabe n, …, 0.
  • Es wird geprüft, ob der aktuelle Wert n gleich null ist.
  • Wenn n = 0 gilt, wird „Happy New Year!!!“ ausgegeben und kein weiterer Funktionsaufruf ausgeführt.
  • Wenn n nicht null ist, wird der aktuelle Wert ausgegeben und der Countdown fortgesetzt.
  • Zuerst gibt die Funktion n aus.
  • Danach ruft sie CountDown(n − 1) auf.
  • Bei einem Startwert von 10 entstehen die Aufrufe für 10, 9, 8, …, 1 und schließlich 0.
Feed/

How can a countdown be written without a loop?

No cover

Channel

Computer science one

1 page

"Suppose we wanted to write a simple program that performed a countdown, printing 10, 9, 8, . . . , 2, 1 and when it reached zero it printed a “Happy New Year” message. Likely our first instinct would be to write a very simple for loop using an increment variable. But suppose we lived in a world without the usual loop control structures that we are now familiar with. How might we write such a program? After thinking about it for a while, we might think: well, we don’t have loops, but we still have functions. In particular what if we had a function that took the “current” value of our counter variable and decremented it, passing it to another function, which did the same thing. For example, we could pass 10 to such a function, which would then subtract 1, passing 9 to another function and so on. A check could be made to see if the value was zero, in which case we print our special message and no longer call any more functions. In fact, we would not need to define 10 different functions to do so. Instead, we could define one function that called itself . It might look something like Algorithm 11.1. Input : An integer n ≥ 0 Output : A countdown of integers n, . . . 0 1 if n = 0 then 2 output “Happy New Year!!!” 3 else 4 output n 5 CountDown ( n − 1) 6 end Algorithm 11.1: Recursive CountDown ( n ) Function"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.