You have to use return statements to make recursive functions make a lick of sense.
Code:
void func(int n)
{
if (n != 0) {
func(n / 2);
putchar ('0' + n % 2);
}
return;
}
Now let's suppose that we are going to call func(5)...
1. Call func(5). We now enter the 1st instance of func.
2. Check (5 != 0)? TRUE
3. Therefore call func(2). We now enter the 2nd instance of func.
4. Check (2 != 0)? TRUE
5. Therefore call func(1). We now enter the 3rd instance of func.
6. Check (1 != 0)? TRUE
7. Therefore call func(0). We now enter the 4th instance of func.
8. Check (0 != 0)? FALSE
9. Therefore we skip the body of the if, and return to caller, terminating the 4th instance of func.
10. The caller was the 3rd instance of func, the command after func (1) is purchar ('0' + 1 % 2), so we putchar ('1').
11. Next command is return to caller, terminating the 3rd instance.
12. The caller was the 2nd instance of func, the command after func (2) is purchar ('0' + 2 % 2), so we putchar ('0').
13. Next command is return to caller, terminating the 2nd instance.
14. The caller was the 1st instance of func, the command after func (5) is purchar ('0' + 5 % 2), so we putchar ('1').
15. Next command is return to caller, terminating the 1st instance.
Now, looking at all the observable actions which we've done, we've printed "101" (10, 12, and 14).
func will not call itself forever because eventually it is going to have to call func(0), and when it does that, it returns without calling itself.
Also, there's an error in your code, which is causing the fault
Code:
scanf("%d",q); // ??
// scanf ("%d", &q);
As a final point, I'd like to say that this is a frighteningly confusing example of a recursive function.