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.

Lakshmi said:   9 years ago
I can't understand. Please explain this.

Priya said:   9 years ago
I can't understand. Please help me.

BhavadipGothadiyaBG said:   8 years ago
How it's Possible?

Lakshay said:   9 years ago
The answer should be 0,1,2,1.

Naseema said:   9 years ago
@Imran Mohammed,
I can't understand how does it prints(1) when the fun(-1) condition fails (in 10 & 11 steps).
Can someone explain it to me?

Thenu said:   9 years ago
@Imran Mohammed.

Understood clearly, Thanks a lot.

R.K said:   9 years ago
@Sree.

Excellent explanation, Thankyou.

Bala said:   9 years ago
Thanks, @Ritesh.

Your deep explanation clears all my doubt.

Ssh said:   1 decade ago
@RAJ explaination is easy to understand.

I would like to know. Is variable n a local variable whose value is flushed at the end of each function call?

Because after printing 0. Next statement is again fun (--n) ; where n becomes -1;

Now -1>0 condition fails.

Now stack points to next statement in function FUN (1) i.e. printf ("%d, ", n);

So why does it print 1 instead of -1.

Debalina said:   1 decade ago
@Vishal and @Sree I don't really get it for step 3.

In step 3 it should not print anything rather exit from the function, so how will zero be printed?

After all the print statement is within the if block?


Post your comments here:

Your comments will be displayed after verification.