C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 4)
4.
What will be the output of the program?
#include<stdio.h>
int reverse(int);

int main()
{
    int no=5;
    reverse(no);
    return 0;
}
int reverse(int no)
{
    if(no == 0)
        return 0;
    else
        printf("%d,", no);
    reverse (no--);
}
Print 5, 4, 3, 2, 1
Print 1, 2, 3, 4, 5
Print 5, 4, 3, 2, 1, 0
Infinite loop
Answer: Option
Explanation:

Step 1: int no=5; The variable no is declared as integer type and initialized to 5.

Step 2: reverse(no); becomes reverse(5); It calls the function reverse() with '5' as parameter.

The function reverse accept an integer number 5 and it returns '0'(zero) if(5 == 0) if the given number is '0'(zero) or else printf("%d,", no); it prints that number 5 and calls the function reverse(5);.

The function runs infinetely because the there is a post-decrement operator is used. It will not decrease the value of 'n' before calling the reverse() function. So, it calls reverse(5) infinitely.

Note: If we use pre-decrement operator like reverse(--n), then the output will be 5, 4, 3, 2, 1. Because before calling the function, it decrements the value of 'n'.

Discussion:
34 comments Page 3 of 4.

Saurabh gupta said:   9 years ago
I agree with you @@Bhavna. The output should be 5,5,4,4,3, 3,2,2,1,1.

Subasri said:   8 years ago
void myfunc(int x){
if(x>0)myfunc(--x);
printf("%d",x);
}
int main()
{
myfunc(5);
return 0;
}

output: 001234


Anyone, please explain this.

Amrendra said:   8 years ago
The function runs infinetely because the there is a post-decrement operator is used. It will not decrease the value of 'n' before calling the reverse () function. So, it calls reverse (5) infinitely. And print 5 5 5 5 to infinity.

Savita said:   8 years ago
Thanks for your explanation @Atul.

MOHIT THAPAR said:   8 years ago
The reverse is a function with return type int. Hence it will produce an error.

Tushar said:   8 years ago
How we will know that function is 'recursive' ?

Chetan said:   8 years ago
@Mohit Thaper & @Tushar.

D is correct answer.

As no is 5. So it is transferred to function, where it does not equal to 0. Then control goes to else part and prints 5. After that post operator used. Hence, it simply transfers same value i.e. 5 and again same process continue. It continuously produces 5.
(1)

Shubham said:   7 years ago
It continously print 5.

Because the characteristic of post decrement is that it gets implement after all operation executed so it fist call recusively then it decrement the no but now again reverse function gets 5 as a fresh no and tgis process continues.

Akshatha patil said:   6 years ago
Thanks @Manraj.

Swetha said:   6 years ago
When the function is repeating continuously why can't the stack overflow?

How it becomes infinite?


Post your comments here:

Your comments will be displayed after verification.