C Programming - Functions - Discussion

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);
    }
}

[A]. 0, 2, 1, 0,
[B]. 1, 1, 2, 0,
[C]. 0, 1, 0, 2,
[D]. 0, 1, 2, 0,

Answer: Option D

Explanation:

No answer description available for this question.

Subu said: (Sep 16, 2010)  
Please explain this.

Sree said: (Sep 24, 2010)  
// typedef int (*pf) (int, int);
// int proc(pf, int, int);

The above two statement has no effects , because they are not used in main or sub function.

Function calls are stored in stack, that is LAST IN FIRST OUT.

1.fun(a=3)---calling sub function--->fun(n=3).
2.fun(3)->if(3>0)true{fun(2)-->step 3,print(n),fun(--n)//active}
3.fun(2)->if(2>0)true{fun(1)-->step 4,print(n),fun(--n)//active}
4.fun(1)->if(1>0)true{fun(0)-->step 5,print(n),fun(--n)//active}
5.fun(0)->if(0>0)false;
6.From step 4,{fun(n=0)//finished,PRINT(n=0),fun(-1)-->step 7}
7.fun(-1)->if(-1>0)false;
8.From step 3,{fun(n=1)//finished,PRINT(n=1),fun(0)-->step 9}
9.fun(0)->if(0>0)false;
10.From step 2,{fun(n=2)//finished,PRINT(n=2),fun(1)-->step 11}
11.fun(1)->if(1>0)true{fun(0)->step 12,print(n),fun(--n)//acti}
12.fun(0)->if(0>0)false;
13.From 11,{fun(n=0)//finished,PRINT(0),fun(-1)-->step 14}
14.fun(-1)->if(-1>0)false;

// all active calls are called and removed from stack.
// here 'n' is a local variable for each function.
// The printing statements are capitalized

PRINT(n=0),PRINT(n=1),PRINT(n=2),PRINT(n=0).

Kavita said: (Sep 26, 2010)  
Thanks Sree.

Lakshmi said: (Nov 27, 2010)  
Sree i didnt get wat u r saying.Plz can u explain me in brief.

Bagesh Kumar Bagi said: (Dec 1, 2010)  
Any one explain again?

Rupinder said: (Dec 16, 2010)  
I think this answer is wrong becouse Printf statement will never executed.this is a recursive function and function all itself again and again in if statement.wen if condition false then it stop execution.this output is wrong.

Popat said: (Jan 8, 2011)  
Its correct answer Thanks Sree

Anusha said: (Jan 11, 2011)  
@SREE:.

How can it execute the printf statement when the condition in if goes false at step 5. Can you explain please.

Sumit Pankaj said: (Jan 15, 2011)  
Please explain once more

Rakesh said: (Jan 31, 2011)  
Sree is absolutely right. Nice one. Good logic.

Nikunj said: (Feb 26, 2011)  
Really good efforts.

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

Anu said: (Mar 2, 2011)  
I too think sree is right... but yes.. we need a more elaborate explanation... pls...

Shanmugapriya said: (Mar 7, 2011)  
Please explain it in clear.

Wikiok said: (Mar 19, 2011)  
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: (May 29, 2011)  
Please explain it clearly.

Vishal said: (Jun 11, 2011)  
Friends if we change the (--n) to (n--) after the printf statement

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

Rohan said: (Jun 14, 2011)  
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: (Jun 27, 2011)  
@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: (Jul 8, 2011)  
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: (Jul 31, 2011)  
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.

Siva Pavan said: (Sep 15, 2011)  
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: (Sep 17, 2011)  
Thank you imran. But this one really seems to be complicated for the beginner level. Your explanation is really helpful one.

Pavithra said: (Sep 29, 2011)  
There is not return statement of any kind so I think this whole code won't execute.

Aparajita said: (Oct 6, 2011)  
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: (Oct 11, 2011)  
Thanx aparajita !!!

Shivanand said: (Nov 6, 2011)  
Can any one explain in simple way ?

Rupinderjti said: (Dec 1, 2011)  
Amazing sree......this is called CODING IN DEPTH.

Saurabh said: (Jan 1, 2012)  
Thanks imran it really cleared my doubt.

Raku said: (Jan 4, 2012)  
Thanks Sree bro

Rathika.B said: (Jan 8, 2012)  
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.

Parth said: (Jan 23, 2012)  
Thanks sree.

Piya said: (Feb 7, 2012)  
Please any one explain in breif clearly.

Dhananjay said: (Mar 6, 2012)  
Thanks sree.

Rupinderjit Singh said: (May 20, 2012)  
@Rathika.B: Well your query is genuine and it is compiler dependent.
And It is not mentioned in standard C, that, in what order sequence will execute.
So it's answer is UNDEFINED.

Shailendra said: (Jun 4, 2012)  
fun(3)-1. fun(2)----1.fun(1)-----1.fun(0)
2. printf 2 2.printf 1 2.printf 0
3. fun(1) 3.fun(0) 3.fun(0)

So at first 1. step will execute. fun(3)->fun(2)->fun(1)->fun(0)=0
2.pf 0 -> 3. fun(0)=0 so print 0
Then it will return last statement fun(1).... 1. completed
2. pf 1
3.fun(0)
Now it will return at fun(2)-- 1. completed
2. pf 2
3. fun(1)-->1.fun(0)
2.pf 0
3.fun(0)

Ritesh said: (Jun 8, 2012)  
Lets change the same program bit differently for understanding the concept properly.....

#include<stdio.h>
void fun(int);
typedef int (*pf) (int, int);
int proc(pf, int, int);

int main()
{
int a=3;
fun(a); // here the value of a is 3 which is passed to n
return 0;
}
void fun(int n) //here the value obtained is 3 so n=3
{
if(n > 0) //condition is 3>0 hence true, enters the loop
{
fun1(--n); //here value of n = 2 and calls function fun1
printf("%d,", n); //prints 2 after the call function is returned
fun4(--n); //here value again becomes 1
}
}

void fun1(int m) //here the value obtained is 2 so m=2
{
if(m > 0) //condition is 2>0 hence true, enters the loop
{
fun2(--m); //here value of m = 1 and calls function fun2
printf("%d,", m); //prints 1 after the call function is returned
fun5(--m); //here value becomes 0
}
}

void fun2(int p) //here the value obtained is 1 so n=1
{
if(p > 0) //condition is 1>0 hence true, enters the loop
{
fun3(--p); //here value of p = 0 and calls function fun3
printf("%d,", p); //prints 0 after the call function is returned
fun4(--p); //here value again becomes -1
}
}

void fun3(int q) //here the value obtained is 0 so n=0
{
if(q > 0) //condition is 0>0 hence false, func ends and goes back to fun2 func to printf statement.
{
same codes here which are not executed....
}
}


So if u see the values printed here is 0 from fun2 then 1 from fun1 and 2 from fun.... as u can see if the input given to func is 3 it prints 2, if input is 2 then it prints 1 and when input is 1 it prints 0. So when fun2 is printed and the value of p becomes -1 it prints nothing and when it prints 1 from fun1 value of m becomes 0 and prints nothing. But when the value 2 is printed in fun, the value of n becomes 1 so it prints 0 again.

So the output will be :
0,1,2,0,

All the option given in above problem is wrong because, after every no is printed a "," comma should be printed as per the program. But in the option 'D', comma is not given after last zero. In programming even a comma matters a lot.

In the above program all the variables that i declared are taken same and function is called repeatedly instead of calling it with different names like i did.. I just gave diff names so that u will understand the flow. I hope u no the flow of the program when the function is called. I hope u understood the logic. Thank you.

Maggi said: (Jun 20, 2012)  
Thank you rithesh. Good explanation. :).

Shashi said: (Jul 17, 2012)  
I will try to explain:

First note that for these things:
1. fun(0) will not execute.
2. fun(1) will only print 0 i.e. --n.

Now follow the tree

fun(2)----> fun(1) -----> print 0
print 1
print 2

fun(1)----> print 0

So output would be 0 1 2 0

Saidattu G said: (Jul 23, 2012)  
void fun(int n) is a function
and in this function we again calling fun(--n)

Means it is a recursive function

Here the condition if(n>0) again check

This works as a loop till condition is false

That means till i=0

Then it prints 0

After print again we are calling fun(--n)

Now 2 loops have to execute so

Finally it prints 120.

Jhunu said: (Aug 19, 2012)  
Thanks Ritesh. You are excellent.

Divyasree said: (Aug 26, 2012)  
Its very confusing Rithesh. I can't able to undstand the flow of excecution. Can anyone explain it clearly?

Rajendra said: (Aug 30, 2012)  
Thanks Sree

Malligadu said: (Sep 6, 2012)  
Thank you kavita.

Mahesh Vanol said: (May 16, 2013)  
fun(3) //upside fun() running
if(3>0)
fun(2) //upside fun() running
if(2>0)
fun(1) //upside fun() running
if(1>0)
fun(0) //upside fun() running
if(0>0) false
so return; //upside fun() finished
"print == 0"

fun(-1) //Now downside fun() running
if(-1>0) false
so return; //Downside fun() finished
"print == 1" //BCoz Inside the fun(1) block fun(0)

if(0>0) false
so return; //Downside fun() finished
"print == 2" //BCoz Inside the fun(2) block fun(1)

if(1>0)
fun(0) false
so return;
"print == 0" //BCoz Here last n=0
fun(-1)
if(-1>0) false
so return; //Downside fun() finished

OUTPUT == 0,1,2,0

Ansh said: (Aug 18, 2013)  
Can someone please explain this in the most simple manner?

Raneesh said: (Sep 22, 2013)  
First of all thanks sree for explaining.

Now if we can understand how 0 is printed first then we can understand the whole program.

BRIEFED ANSWER IS IN STEP 3 MUST READ

Firstly if you can figure out this program you can understand above one.

FUNCTION A(INT N)
{
IF(N>0)
{
FUNCTION B() // calls function b
PRINT STATEMENT
}
}

1. Function b is called

2. Function b fails.

3. FUNCTION B RETURNS TO IF STRUCTURE AFTER FAILING AND THEN PRINT STATEMENT EXECUTED and 0 is printed.

4. Then further functions called.

Rishabh said: (Oct 26, 2013)  
In step 5 the condition of if gets failed. Means it doesn't enter in its body. So how the output will generate?

Please explain.

Shafeeq said: (Dec 8, 2013)  
Any simple method to find output of function with recursion?

Arnab said: (Mar 6, 2014)  
You can arrange each function call in a block and then understand it becomes easy,

As fun(3)---->fun(2)----------->
printf(2)
fun(1)

//After encountering parentheses return to the next line of the calling function.

Vik said: (Apr 21, 2014)  
PRINT(n=0), PRINT(n=1), PRINT(n=2), PRINT(n=0).

Abhi_027 said: (Apr 22, 2015)  
How can it be printed as recursive function is executed repeatedly calling & at last the program is ended with false statements?

Raj said: (May 5, 2015)  
Step 1: fun (3) ->3>0.

1.1: fun (2) ->2>0, still lines left to be processed.

1.2: fun (1) ->1>0, still lines left to be processed.

1.3: fun (0) ->0>0, condition fails comes to the next line print the current value of n (i.e. ) n=0; prints 0, next fun (-1) comes out of the current 1. 3 loop.

Now again going back to unprocessed lines in step 1.2,

1.2: Unprocessed line here in this call starts from printf. For this loop n value is 1; prints 1, & comes to next line.

fun (--n) ->fun (0) 0>0 fails. 1.2 loop ends here.

Now again going back to unprocessed lines in step 1.1,

1.1: Unprocessed line here in this call starts from printf. For this loop n value is 2; prints 2, & comes to next line.

fun (--n) ->fun (1) ; once again calling the function fun (1).

1st line - decremented the value to 0;

2nd line prints the value; (prints 0,).

3rd line - fun (-1) totally terminates everything.

Final o/p : 0, 1, 2, 0.

Vishal said: (Jun 4, 2015)  
if(3>0) true.
step:1 fun(2).
if(2>0) true.
step:2 fun(1).
if(1>0) true.
step:3 fun(0).
if(0>0) false.

print 0 from step:3, fun(-1) false.
print 1 from step:2, fun(0) false.
print 2 from step:1, fun(1)->fun(0).
print 0 from fun (0) at second last line.

Debalina said: (Aug 15, 2015)  
@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?

Ssh said: (Aug 20, 2015)  
@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.

Bala said: (May 20, 2016)  
Thanks, @Ritesh.

Your deep explanation clears all my doubt.

R.K said: (May 23, 2016)  
@Sree.

Excellent explanation, Thankyou.

Thenu said: (Jun 16, 2016)  
@Imran Mohammed.

Understood clearly, Thanks a lot.

Naseema said: (Oct 2, 2016)  
@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?

Lakshay said: (Oct 5, 2016)  
The answer should be 0,1,2,1.

Biru said: (Oct 12, 2016)  
Not able to understand it. Can anyone help me?

Priya said: (Nov 6, 2016)  
I can't understand. Please help me.

Lakshmi said: (Nov 18, 2016)  
I can't understand. Please explain this.

Vinesh Chauhan said: (Jan 18, 2017)  
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.

Surya Mitthu said: (Feb 20, 2017)  
I don't understand this. Please someone explain this to me.

Abhijit Dey said: (Mar 13, 2017)  
Good explanation, Thanks @Sree.

Manu said: (Apr 5, 2017)  
I got it as 0,1,0,2,0,1,0.

How? Please tell me.

Fenil said: (May 5, 2017)  
Can anyone explain in brief?

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

Vidya said: (May 25, 2017)  
Well said @Sree. Thanks.

Manjunath Rk said: (Jun 16, 2017)  
Good explaination, Thanks @Sree.

Khan said: (Jun 29, 2017)  
When 0>0 the if statement fails then how the statements inside it will execute?

Insiya said: (Aug 15, 2017)  
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.

Asha said: (Sep 19, 2017)  
Thank you guys. I understood stack.

Kowsik said: (Sep 19, 2017)  
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.

Bhavadipgothadiyabg said: (Sep 26, 2017)  
How it's Possible?

Tushar said: (Nov 4, 2017)  
How does calling function works ?

Naresh said: (Dec 7, 2017)  
I am not getting what happens after f (0). How will the output be 0 1 2 0?

Sandy said: (Dec 24, 2017)  
@ALL. According to me.

void f(3){
if(3 > 0)
{
f(2) //the first fun(--n) // ((when you are on this line directly go to f(2) and if that executed then execute the below line))
print(2);
f(1)//the second fun(--n)((when you are on this line directly go to f(1) and if that executed then execute the below line))
}
}

=========================================================

void f(2){
if(2 > 0)
{
f(1) // ((when you are on this line directly go to f(1) and if that executed then execute the below line))
print(1);
f(0) // ((when you are in this line directly go to f(0) and if that executed then execute the below line))
}
}
=========================================================
void f(1){
if(1 > 0)
{
f(0) // ((when you are in this line directly go to f(0) and if that executed then execute the below line))
print(0);
f(-1) // i am not writing this function as it will never be executed because it will not cross if(-1 > 0).
}
}

=========================================================
void f(0)
{
if(0 > 0) { go back simon !!! } //this will never be executed so ever encounter the f(0) remember its nothing.
}
=========================================================

Malavika said: (Jan 8, 2018)  
Please, can anyone explain clearly? because after printing 0 then the value becomes -1. After the process, I did not understand.

Shaheen Khan said: (Jan 26, 2018)  
I understood till 0 gets printed someone please explain after printing of 0 where does the call goes and how it works?

Shahid said: (Jan 27, 2018)  
Output is wrong, it's a recursive function.

Krishan Kumar said: (Mar 23, 2018)  
Please, go through function stack calls:-so for given problem here is the solution.

{
please reff to signs as folows
--1-->function call to upper fun();
<--1--return back to upper fun();
--2-->function call to lower fun();
<--2--return back to lower fun();
}

1>from main() :-fun(3) condition is true till as fallows==fun(3)--1-->fun(2)--1-->fun(1)--1-->fun(0) as now n=0 condition is false so the function return to calling function fun(0); with n=0;because if condition is false so nothing to do in that stack fun(0)is completed fun(1)<--1--fun(0).

And execute next statement printf(n=0);

And after that our stack is fun(1)--2-->fun(-1)
Which is again false so nothing to do fun(-1) terminated due to this completion we have executed fun(1) with n=1;

And execute next statement printf(n=1) and with n=1 next statement is fun(0) calling which is again false so nothing to do ;as off now we are done with fun(1).

fun(3)--1-->fun(2)<--1--fun(1) as we return to fun(2) the next statement is printf(n=2) with n=2 we call 2nd one fun(1) which calls again with n=1 so if condition is true calls fun(0) (upper) condition is false so return and execute next statement printf(n=0); so after this execution all the condition is false so we returned to main() function .

fun(3)--1-->fun(2)--1-->fun(1)--1-->fun(0)(false)
print(0)
fun(-1)false both are false return to fun(1)
Next print(1) then next is fun(0) call (false)so fun(1) is complete
fun(3)--1-->fun(2) next is print(2) --2-->fun(1)(true) --1-->fun(0)(false) next is printf(0);after this statement we are just returning to the lower fun() call.

So nothing to print.

Mukunda Saini said: (Mar 29, 2018)  
According to me, It is;

fun(3)->fun(2) -> fun(1) -> fun(0)
print 2 print 1 print 0 finish
fun(1)-> fun(0) fun(-1)
print 0 finish finish
finish

Guddi said: (Jun 20, 2018)  
I don't understand. Please explain to me.

Nikk said: (Aug 4, 2018)  
If 3>0 then --it will call fun(2) & fun(2) call fun(1)& fun(1) call fun(0)
then fun(0)returns 0 to fun(1),it will print(0), After that how the flows goes?

Please explain it.

Rajarshi said: (Aug 7, 2018)  
Here, we can Apply the concept of recursive tree.

Vinith Kumar said: (Oct 5, 2018)  
Simply great @Mukunda Saini.

Harish Mahajan said: (Oct 16, 2018)  
How can I recognize a function is a recursion?

Please explain me.

Anil said: (Oct 25, 2018)  
It is a stack concept.

When n=3 then it becomes 3,2,1,0 as per condition, these values are stored in the stack
0 1 2 3.

When the condition becomes false then automatically values are poped. Here top value is 0 or last inserted so 0 is first poped and execution jumps to print function and display 0 and same for all.

At last output will be;
0 1 2 0

Tejashri said: (Dec 11, 2018)  
Hi, please explain this program in simple way.

Fuad Al Masud said: (Jan 6, 2019)  
Can anyone explain the program in detail?

Mohan said: (Jul 5, 2019)  
I have a doubt when the functions are called recursively each time n value decremented by 1 hence finally it comes 0 so now n value in fun (0) is 0 so now n=0 then how it prints 1 2 in fun (1) fun (2) because here also n must be 0 how it happens? Please tell me.

Hardik said: (Sep 20, 2019)  
@Raj.

Your explanation is the best. Thanks.

Sudheer said: (Jun 23, 2020)  
If you use stack concept then question contain stack key.

The Correct answer for this question is, no output. Because if the condition is true then the loop will be created. If the condition is false(n=0)it do not execute if condition. Then how control goes to printf()?

Sanjib Kumar Mandal said: (Aug 7, 2021)  
Thanks all for giving the explanation.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.