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

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

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)

Hardik said:   6 years ago
@Raj.

Your explanation is the best. Thanks.
(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)

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

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)


Post your comments here:

Your comments will be displayed after verification.