How write a recursive print program

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

    This question is quite old, yet none of the answers answer the actual question, viz. solving the problem in C using recursion only, without explicit loops.

    Here is a simple solution obtained by fixing the misunderstanding present in the original code (confusion between two possible functions of "print"). There are no explicit loops.

    #include 
    
    void countto(int n)
    {
            if(n != 0)
            {
            countto(n-1);
            printf("%d",n);
            }
    }
    
    void triang(int n)
    {
            if(n != 0)
            {
                    triang(n-1);
                    printf("\n");
                    countto(n);
            }
    }
    
    int main()
    {
            triang(4);
    }
    

提交回复
热议问题