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 4 of 10.

Abhijit Dey said:   8 years ago
Good explanation, Thanks @Sree.

Surya mitthu said:   9 years ago
I don't understand this. Please someone explain this to me.

Vinesh Chauhan said:   9 years ago
Great logic @Sree and other friends who explain this.

Actually, when first time fun (3); is executed the control transfer to int fun (int n) right.
Then in side of the definition of fun there is another fun() which is fun(--n). So the value of n=2 then again called fun (2) this loop is condition until value of n is equal to 0 then the control passes to printf() because when ever recursion of the function proceeds after that the control return to that point from where it called that's why printf will called value with 0.

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

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

Biru said:   9 years ago
Not able to understand it. Can anyone help me?

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.


Post your comments here:

Your comments will be displayed after verification.