How write a recursive print program

前端 未结 8 2065
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 16:02

Gurus,

I want to know how to write a recursive function that prints

1
12
123
1234
...
......

For eg: display(4) should print

8条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 16:42

    To define a recursive function, you have to do three things:

    1. Define what the function does. In this case it is printing numbers from 1 up to n.
    2. Define what the recursive call is. What happens the next time around? The easiest way is to think from the bottom up; in this case, on each earlier line, it is printing numbers up to one less than the previous. Therefore, every time you call the function again, you want to call it with one less than the previous number.
    3. Define your stop condition. When should I stop recursing? In this case, once you hit the number 1, this will be your last iteration. This means, we want to call the recursive function until this stop condition is reached - or in other words, while n is greater than 1.

    Therefore, we end up with the following algorithm:

    function display(n):
        if(n > 1):
            display(n-1);
    
        print 1..n;
    

提交回复
热议问题