How write a recursive print program

2020-05-10 09:08发布

问题:

Gurus,

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

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

For eg: display(4) should print

1
12
123
1234

Code

#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);
}

Output
1

12

1

123

Issues

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

Update

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.

回答1:

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;


回答2:

EDIT: OK, I improved my answer with the guidelines of @lc.

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


回答3:

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 <stdio.h>

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);
}


回答4:

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;
}


回答5:

The recursive function used here is func(int). Initially the value is passed from the main() program. The recursion occurs till we reach the exit condition , which is val=0 in this case. Once we reach that level , we move the penultimate frame a print "1". The same pattern is followed to attain the sequence "1 2". . . "1 2 3 " . . . "1 2 3 4"

int func(int val){

        int temp,i;

        if( val == 0 )
        {
                val++;
                return val;
        }
        else
        {
                val--;
                temp=func( val );

                for (i=1;i<=temp;i++)
                {
                        printf("%d",i);
                }
                printf("\n");

                temp++;
                return temp;
        }
}

int main(){

        int value=4, result;

        result=func(value);
}


回答6:

Just for fun, here's a purely recursive solution. It's in python, which is practically pseudocode anyway. (Non-pythonic newlines are for clarity).

def loop(max, row=1, col=1):
    if col <= row:
        print col,
        loop(max, row, col+1)
    elif row < max:
        print "\n",
        loop(max, row+1, 1)
    else:
        print "\n",


回答7:

#include<stdio.h>
void print_num(int x);
int n;
void main(){
printf("Enter number of lines: ");
scanf("%d",&n);
print_num(1);
}
void print_num(int x){
int i;
for(i=1;i<=x;i++){
printf("%d",i);
 }
if(x<n){
printf("\n");
x++;
print_num(x);
 }
}

This is simple, right?



回答8:

void display(int k)
    {
         if (k < 1) { return; }
         display(k-1);
         for (int i = 1; i <= k; i++)
         {
         cout << i;
         }
         cout << endl;

    }


    int main()
    {
        int a = 4;
        display(a);
        return 0;
    }


标签: c recursion