How write a recursive print program

前端 未结 8 2066
没有蜡笔的小新
没有蜡笔的小新 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:27

    We keep calling PrintIt() with the argument-1 recursively until x < 1. Each call will then return in reverse order when x < 1. At each return we print a line starting at 1 to x.

    #include "stdio.h"
    
    void PrintIt( int x )
    {
        int i;
        if( x > 1 )
        {
            PrintIt( x - 1 );
            printf("\n");
        }
    
        for( i = 1; i < x+1; i++)
        {
            printf("%d", i);
        }
    
        return;
    }
    
    int main(int argc, char *argv[])
    {
        PrintIt( 4 );
        return 0;
    }
    

提交回复
热议问题