# Thread: Recursive function, trying to understand the logic.

1. ## Recursive function, trying to understand the logic.

I have been given this function and I am trying to understand the logic behind it. I was given: puzzle(25) and puzzle(38); and the following code:
Code:
```void puzzle (int n)
{
if (n!=0)
{
puzzle (n/2);
putchar ('0'+n%2);
}
}```
I added a print statement and my outputs are, 11, 13, 06, 012 & 125 for puzzle(25) and 11, 02, 04, 19, 119 and 038 for puzzle(38). I am assuming i did this function correctly by havint it printf the (int n) value.

Can someone help me with this? I really appreciate it and thanks!

2. Depends on what puzzle() is supposed to be doin'.

3. Out of curiosity, but are you familiar with binary and bit shifting?

4. What about the logic don't you understand. Do you have the basics of recursive programming? Do you understand what n/2 and n%2 do (and the other uses for n%2)? Do you understand the putchar statement? Please be a little more specific.

5. Originally Posted by itCbitC
Depends on what puzzle() is supposed to be doin'.
I believe that is what my question is. What is the function 'puzzle' doing. I am trying to understand the logic behind it. This is the code I did in order for it to print;
Code:
```#include <stdio.h>

void puzzle (int n);

void puzzle (int n)
{
if (n!=0)
{
puzzle (n/2);
putchar ('0'+n%2);
printf ("%d\n", n);
}
}

int main()
{
puzzle (38);
}```

6. Run it on your system w/o the printf() and correlate its output to the binary number system.

7. Help with the logic? The function repeatedly calls itself, each time doing so passing half the value it was previously called with until the value passed equals 0. Once it reaches 0, the function begins to exit, printing values as it goes - either 0 or 1 depending on whether the argument passed in to that particular instance of the function was even or odd. What you are left with (in the original version, not your "modified" version) should be a sequence of 0's and 1's that represent the original argument expressed in binary form. 25 (decimal) is 11001 in binary, 38 (decimal) is 100110 in binary.

8. Thank you itCbitC and hk_mp5kpdw.