Concept
How can a countdown be written without a loop?
ComputerScienceOne / Recursion
"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"
Related Ideas
- How can recursive functions be written in C?ComputerScienceOne · Recursion
- How is recursion implemented in Java?ComputerScienceOne · Recursion
- What is a recursive CountDown function?ComputerScienceOne · Scaling a Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- How can recursion be made tail-recursive in C?ComputerScienceOne · Recursion
- How can a recursive method sum the elements of an array?ComputerScienceOne · Recursion
- How can you implement ordinary and tail-recursive summation functions in PHP?ComputerScienceOne · Recursion
- How can Fibonacci numbers be computed recursively in Java?ComputerScienceOne · Recursion
- How is memoization implemented for recursive Fibonacci in C?ComputerScienceOne · Recursion