How write a recursive print program

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

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

提交回复
热议问题