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

Nikunj said:   1 decade ago
Really good efforts.

I understood the concept of stack but please expand it more for better understanding!

Anu said:   1 decade ago
I too think sree is right... but yes.. we need a more elaborate explanation... pls...

Shanmugapriya said:   1 decade ago
Please explain it in clear.

Wikiok said:   1 decade ago
If the program returns from the first "fun(--n)" function it will continue running to printf statement, and then the other fun(--n) statement comes.

Sony said:   1 decade ago
Please explain it clearly.

Vishal said:   1 decade ago
Friends if we change the (--n) to (n--) after the printf statement

Then check the answer and explain it plz..........

Rohan said:   1 decade ago
Plz explain sree. I may be wrong.

But condition (if 3>0)okk then function executed

fun(--3)=fun(2) okk no return statement so printf will execute

So value of n will be ...n=2 so n will be print 2 first m not understanding how 0 is printed.

Please explain.

Parveen said:   1 decade ago
@Rohan..... i m 100% satisfied with rohan coz there is no matter to print 0 in answer. look at the condition..if(n>0)... then how it can enter inside the loop. Any one please explain this completely.

Terry said:   1 decade ago
Parveen, I can't explain it completely but if n=1 then it can get in the if(n>0), once inside fun(--n) is called which after return from fun means n is 0 and hence zero gets printed.

IMRAN MOHAMMED said:   1 decade ago
Guys, consider the recursive function (which was called in another function), as a separate new function which was defined in the same manner as the other one. Just try to check the condition at each step and proceed to the next statement. The entire code can be considered as follows :

fun(3)
{
if(3>0)
{
fun(2)
{
if(2>0)
{
fun(1)
{
if(1>0)
{
fun(0)
{
if(0>0)//CONDITION FAILS
}
print(0) //PRINTS 0 FIRST
fun(-1)//CONDITION FAILS
}

}
print(1)//PRINT 1 EXECUTES SECOND
fun(0)// CONDITION FAILS ( 2nd fun(--n) in fun())
}
}
print(2)// PRINT 2 EXECUTES THIRD
fun(1) //( from 2nd fun(n--))
{
if(1>0)
{
fun(0)// CONDITION FAILS
print(0)// PRINT 0 EXECUTES FORTH
fun(-1) // CONDITION FAILS
}
}

}

}


Now just check each condition and the print statement which is executed next. Hope my expalanation is clear.


Post your comments here:

Your comments will be displayed after verification.