如何写一个递归打印程序 [英] How write a recursive print program

查看:120
本文介绍了如何写一个递归打印程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大师,

我想知道如何编写一个递归函数,它打印

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

1结果
12结果
123结果
1234结果
...结果
......结果
结果
对于如:显示器(4)应打印

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

For eg: display(4) should print

1结果
12结果
123结果
1234结果

1
12
123
1234

#include <stdio.h>

void print(int n)
{
        if(n != 0)
        {
                print(n-1);
                printf("\n");
                print(n-1);
                printf("%d",n);
        }
}
int main()
{
        print(3);
}

输出
结果
1结果
结果
12结果
结果
1结果
结果
123搜索

Output
1

12

1

123

我想写一个纯递归 (没有任何环)的功能,但无法过滤不需要的打印。
希望有人帮助我!

I wanted to write a pure recursive (without any loop) function but unable to filter unwanted prints. Hope someone will help me out!!!

感谢所有这些均给予好像我们可以写一个只用递归和需要循环answers.From所有的意见。

Thanks all for the answers.From all the comments which were given it seems like we can write one with only recursion and a loop is required.

推荐答案

要定义一个递归函数,你必须做三件事情:

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


  1. 定义函数做什么。在这种情况下,印数从1到的 N

  2. 定义递归调用是什么。下一阵子会发生什么?最简单的方法是从下往上想;在这种情况下,在每个前面线,就是印刷数最多一小于previous。因此,每次你再次调用该函数的时候,你要一个小于previous数来调用它。

  3. 定义你的停止条件。:当我应该停止递归?在这种情况下,一旦你打1号,这将是你最后一次迭代。这意味着,我们要调用的递归函数的直到的达到这个停止条件 - 或者换句话说,,而的n大于1

  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;

这篇关于如何写一个递归打印程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆