C Programming - Functions - Discussion
#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--);
}
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'.
Reverse function will repeats itself until no becomes zero.
I think output must be 5, 4, 3, 2, 1.
And when no becomes zero, function will exit from loop.
Can you please tell me why we get same output ie infinite in case of post increment and pre increment?
reverse(no--);===>calling processing.
reverse(no);
no=no-1;
So because in that situation before decrement the we called the reverse function in recursive..
Hence the result will be infinite loop.
No chance get decrement.
reverse(--no);==>no=no-1; after that call reverse(no);
So print : 5, 4, 3, 2, 1.
no++ or ++no no effect output infinite.
When reverse (no) is called recursively, it will every time get the value as 5 and not the decremented value as 4, 3, 2 and so on. This is because every time reverse (no) is called, the variable named "no" is a new different variable not the same. The decremented value is in the previous function call (or stack frame) and therefore after calling the reverse (no) we are entering a new stack frame resulting into a new variable "no" which is having a value 5 every time. Hence the result will be infinite loop.
Hope this helped.
I also agree with both of you.
Is the answer is correct ?
If yes then please explain it.