problem on recursion

Predict the output of following program. What does the following fun() do in general?

 int fun(int i) {   if ( i%2 ) return (i++);   else return fun(fun( i - 1 )); }   int main() {   printf(" %d ", fun(200));   getchar();   return 0; } please explain the output

1Comment
Vivek Vikram Singh vivek14 13 Jun 2016 01:53 am

1) fun(200) --> as i%2 will be equal to 0, which is false, so else part is executed and fun(fun(199)) is called, from which inner call will take place first i.e. fun(199) and outer function will use value returned by inner call.

2) fun(199) {Inner Call}  --> as i%2 will be equal to 1, which is true, so return instruction is executed. Now return i++ , return original value of i and then increment the value. So the value returned will be 199 and this value will be used by outer call now.

3) fun(199) {Outer Call) --> same as above. The value, 199, returned by this call will be there in Main and printed.

Output: 199.

The concept is explained above.

Execution output can be seen in link: https://ideone.com/8RlhFe