-4

可能重复:
如何编写递归打印程序

我已经问过这个问题,但由于信息不足,它被关闭了。 如何编写递归打印程序

大师们,

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

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

例如: display(4) 应该打印

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

123

问题

我想写一个纯递归函数,但无法过滤不需要的打印。希望有人能帮帮我!!!

4

2 回答 2

1

这可能是你想要的吗?

#include <stdio.h>

void print(int n)
{
    int i;
    if (n > 0)                  // [2]
    {
        //call print recursively
        print(n-1);             // [3]
        for (i=1; i<=n; i++)    // [4]
            printf("%d",i);
        printf("\n");
    }
}
int main(int argc, char *argv[])
{
    // If no argument, default to 8
    int value=8;
    if (argc > 1 )
        value = atoi(argv[1]);
    print(value);                // [1]
    return 0;
}

编译它并像这样执行:

display 3

或不带任何参数(默认为display 8):

display

诀窍是print(n-1)在打印当前的输出之前调用n。这是执行时的程序流程display 3

<main() function is running>
main() calls print(3) in [1]
   <print(3) is running, n is 3>
   since n>0 in [2] print(3) calls print(2) in [3]
      <print(2) is running, n is 2>
      since n>0 print(2) calls print(1)
         <print(1) is running, n is 1>
         since n>0 print(1) calls print(0)  
            <print(0) is running, n is 0>
            since n=0 print(0) doesn't print anything and returns
            now the function that called print(0) (that is, print(1)) takes over
         <print(1) is running, n is 1, continues executing in [4]>
         print (1) enters the for loop, prints "1\n" and returns
         now the function that called print(1) (that is, print(2)) takes over
      <print(2) is running, n is 2, continues executing in [4]>
      print(2) enters the for loop, prints "12\n" and returns
      now the function that called print(2) (that is, print(3)) takes over
   <print(3) is running, n is 3, continues executing in [4]>
   print (3) enters the for loop, prints "123\n" and returns
   now the function that called print(3) (that is, main()) takes over
<main() is running>
main executes return(0) and exits

这是打印到控制台的内容:

1
12
123

如果您搬家print(n-1)后,printf("\n")您将拥有:

123
12
1
于 2012-10-16T07:16:20.210 回答
0

您可以为此使用以下代码。

#include<stdio.h>

    void rec_print(int n)
    {
     int i=1;
     if(n>0)
     {
      rec_print(n-1);
      for(i=1;i<=n;i++)
            printf("%d",i);
      printf("\n");
     }
    }

    int main()
    {
     int n=5;
     rec_print(n);
     return 0;
    }
于 2012-10-16T07:09:01.100 回答