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.

Tushar said:   8 years ago
How does calling function works ?

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

Kowsik said:   8 years ago
When fun(0) is called 0>0 condition fail and it will not enter in the loop further. So the program will not provide any output. Correct me if I am wrong.

Asha said:   8 years ago
Thank you guys. I understood stack.

Insiya said:   8 years ago
The main thing to b noted here is that once the if the condition fails only the inner function is returned the remaining calling functions r still there.

The value of n is 3 initially
Fun(3)
{
3 > 0 true
{ fun(2) is called
Printf(2)
Fun(1)}
}
Now wat is fun(2) value . we need to find it
So fun(2)
{
2>0 true
{ fun(1)
Print(1)
Fun(0) }

Find fun(1)
{ 1>0 true
Fun(0)
Print(0)
Fun (-1)
}

Find fun(0)
{
0>0 false so function returns
}

Substitution starts from the most inner loop so it will start from fun(0).
So by back substitution 0 is printed then function returns to fun(1) call and prints 1 the goes to fun (0) which returns again as fun(0) fails conditions so the function returns to fun(2) call and prints 2 and the fun(1) and wch brings us to fun(0) and prints 0.

Khan said:   8 years ago
When 0>0 the if statement fails then how the statements inside it will execute?

Manjunath Rk said:   8 years ago
Good explaination, Thanks @Sree.

Vidya said:   8 years ago
Well said @Sree. Thanks.

Fenil said:   8 years ago
Can anyone explain in brief?

As each time function is called & control is passed to function how printf statement will be executed?

Manu said:   8 years ago
I got it as 0,1,0,2,0,1,0.

How? Please tell me.


Post your comments here:

Your comments will be displayed after verification.