# Thread: Tracing through a recursive program in C

1. ## Tracing through a recursive program in C

Say we have the program:
Code:
```#include <stdio.h>

void binary_representation (int n)
{
if (n != 0)
{
binary_representation(n/2);
printf("%d", n%2);
}
}

int main (void)
{
binary_representation(13);
printf("\n");
return 0;
}```

The problem asks for the output of the program
So my process was like:
1) the main function calls binary_representation and sents 13

2) binary_representation(13) passes the conditional if-statement and calls binary_representation(13/2) while printing out 13%2 = 1 in the process

3) binary_representation(13/2) passes the condition statement and calls binary representation(6/2) while printing out (13)%2 = 1 in the process

4) binary_representation (6/2) passes the condition statement and calls binary representation (3/2) while printing out (6/2)%2=0 in the process

5) binary representation (3/2) passes the condition statement and calls binary representation (1/2) while printing out (3/2)%2=1 in the process

6) condition fails, exits the function, main prints a newline and returns zero

Is my solution be a correct interpretation to this program? 2. Make sure you keep your order straight -- "calls binary representation(13/2) while printing out 13%2=1 in the process" isn't possible. It does one thing, then it does the other. 3. No. The recursive calls will all be made, just like you think - but NO printing will be done at all throughout those recursive calls, since the printf() line of code, is done AFTER the recursive call:

Call to binary_r() //push onto the stack
Call to binary_r() "
Call to binary_r() "
Call to binary_r() "
Return and print //pop off the stack
Return and print "
Return and print "
Return and print "

All the printing is done on successive pops off the stack 4. Thanks alot! Popular pages Recent additions 