0

I used the concept of recursive function in the following but from my understanding of the concept, the output of the code should be 0, but the output here is 012345 and I'm not sure how it is working.

Could someone please explain it to me as my College Professor couldn't do so.

#include<stdio.h>
#include<conio.h>

int yo(int a)
{
    if(a>0)
    {
        yo(a-1); //using recursion function
    }

    printf("%d",a); //printing value
}

void main()
{
    yo(5);
    getch();
}
piman314
  • 4,834
  • 18
  • 32
  • 3
    Possible duplicate of [How Recursion works in C](https://stackoverflow.com/questions/5631447/how-recursion-works-in-c) – msc Apr 06 '18 at 06:25
  • 1
    follow the call step by step on paper ... – Ahmed Masud Apr 06 '18 at 06:29
  • 5
    It helps us believe you're serious if you post code that compiles. The ```\\``` 'comment' markers won't compile — you meant `//` I assume. `void main()` also raises hackles; see [What should `main()` return in C and C++](https://stackoverflow.com/questions/204476/) for lots of information. – Jonathan Leffler Apr 06 '18 at 06:31
  • If your professor couldnt explain this then he should probably get fired. – Fredrik Apr 06 '18 at 08:17

2 Answers2

6

The printf is after the recursive call; Hence, the "stack" of a-values with which yo is called is 5,4,3,2,1,0, before the last yo-call with parameter value 0 begins to print; then 1,2,...

Use a debugger and try it out!

Stephan Lechner
  • 33,675
  • 4
  • 27
  • 49
0

first the value of a is 5 when function is called, so this value is stored into stack and condition is checked (5>0) which is true, so next time yo() is called with value 4 and same procedure is repeated until the value of a becomes 0.

now condition is false (0>0), so next statement will be printed with value of a in stack and in stack value is pop like last in first out and will print 012345.