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

Aayush Gajjar said:   2 years ago
@All.

Although It happens simultaneously, Let's understand the concept as per pre-decrement.
There is --n so first n becomes n-1 and then it goes into the recursion function....

if(n > 0)
{
fun(--n);
printf("%d,", n);
fun(--n);
}

Explained :

f(3){
n = 2

f(2){
n = 1

f(1){
n = 0

f(0){
return to f(1)
{
as per value of n of above f(1)
print(0) -> 0

return to f(2)
{
as per value of n of above f(2)
print(1) -> 1

now, n=0

f(0){
return to f(3){
as per value of n of above f(3)
print(2) -> 2

now, n=1
f(1){
n=0
f(0){
return to f(1){

as per recent value of f(1){
print(0) -> 0

now, f(0){
return

return from f(3).

So, the final answer series is 0, 1, 2, 0.
(22)

Sanjib Kumar Mandal said:   4 years ago
Thanks all for giving the explanation.
(1)

Sudheer said:   5 years ago
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()?
(8)

Hardik said:   6 years ago
@Raj.

Your explanation is the best. Thanks.
(1)

Mohan said:   6 years ago
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.
(6)

Fuad Al Masud said:   7 years ago
Can anyone explain the program in detail?

Tejashri said:   7 years ago
Hi, please explain this program in simple way.

Anil said:   7 years ago
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
(4)

Harish Mahajan said:   7 years ago
How can I recognize a function is a recursion?

Please explain me.
(1)

VInith kumar said:   7 years ago
Simply great @Mukunda Saini.


Post your comments here:

Your comments will be displayed after verification.