# Needed a solution on the following Recursive function

• 12-15-2012
Raj 89
Needed a solution on the following Recursive function
In the below mentioned code i am having a difficulty to understand the logic behind it.

Code:

```#include <stdio.h> void call(int n ) { if ( n < 0 ) { call(--n) ; printf("\n%d",n) ; call(--n) ; } } int main(void ) { int a = 3; call(3) ; return 0 ; }```
The output of the code is 0 1 2 0. Why?
• 12-15-2012
heinz55
Actually your code is pure C not C++.

Anyway, this particular code should not give us any output. So it's quite a mystery how did you get this "0 1 2 0".
What compiler are you using?
• 12-15-2012
c99tutorial
As mentioned above, the function as written will give no output if the argument is nonnegative. Notice that even if the argument is negative, this would result in an unendless series of recursive calls resulting in undefined (i.e. system-dependent) number of output lines with various integers. Also, why do you set a = 3 in your main function? Finally, if the program does manage to terminate, it will end in the middle of a line without a terminating newline, which is generally not a nice way to end the program's output.

For recursive functions it helps to identify two cases: the base case and the recursive case. In your call example, you only specified the recursive case "if (n < 0)....". The base case would be a condition to specify where your function will eventually "stop", ending the recursion.
• 12-15-2012
iMalc
Quote:

Originally Posted by Raj 89
The output of the code is 0 1 2 0. Why?

It does not. You have misrepresented the facts.