C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 5)
5.
What will be the output of the program?
#include<stdio.h>
void fun(int);
typedef int (*pf) (int, int);
int proc(pf, int, int);

int main()
{
    int a=3;
    fun(a);
    return 0;
}
void fun(int n)
{
    if(n > 0)
    {
        fun(--n);
        printf("%d,", n);
        fun(--n);
    }
}
0, 2, 1, 0,
1, 1, 2, 0,
0, 1, 0, 2,
0, 1, 2, 0,
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
96 comments Page 3 of 10.

Siva pavan said:   1 decade ago
All are explaining according to the answer. If condition in the if loop fails it completely comes out of it then how can printf statement present in the if loop executes?

Remo said:   1 decade ago
Thank you imran. But this one really seems to be complicated for the beginner level. Your explanation is really helpful one.

Pavithra said:   1 decade ago
There is not return statement of any kind so I think this whole code won't execute.

Aparajita said:   1 decade ago
Whenever the condition fails the it will stop calling the recursive function but it has to come back to the next statement to be executed. In this case after the value of n=0 then it will stop calling fun(--n) but now it will pop the stack and execute the statement next to first fun(--n) function i.e. the printf statement.

Xyz said:   1 decade ago
Thanx aparajita !!!

Shivanand said:   1 decade ago
Can any one explain in simple way ?

Rupinderjti said:   1 decade ago
Amazing sree......this is called CODING IN DEPTH.

Saurabh said:   1 decade ago
Thanks imran it really cleared my doubt.

Raku said:   1 decade ago
Thanks Sree bro

Rathika.b said:   1 decade ago
The compiler uses one data structure called stack for implementing normal variables as well as recursion values.

Eg:
int a=3;
printf("%d %d %d",++a,a,a++);

Do you think what is the o/p of this pgm? We think that o/p is: 3 4 5
But it is wrong. Correct o/p is: 5 4 3. Because of stack implementation. similar way you apply this concept into stack. You got correct ans. So, my small opinion is, whenever we see the recursion function, it's simple way to implement stack concept in our mind, for getting solution.


Post your comments here:

Your comments will be displayed after verification.