Baron
Baron

Reputation: 13

Recursive functions in C and printf

So, first of all I'm a total beginner in C, we're studying it at University on the course 'Structured Programming'.

Now, the last few lectures about 'Recursive functions' have been a pain for me as a beginner. Could anyone of you be kind enough to explain me this:

So I have this little script, a recursive function that takes a decimal number and converts it to a binary one:

#include <stdio.h>

void binary(int num)
{
    if (num == 0) return;

    binary(num / 2);
    printf("%d", num % 2);
}

int main()
{
    int n;
    scanf("%d", &n);
    binary(n);
    return 0;
}

Now I was wondering, how does this function work? I know the logic behind it and whats its supposed to do, but I don't know how it does IT. The printf in the bottom is especially throwing me off, for example if the printf function is before the recursive call, for the input decimal 10 it prints out (0101) but if its under it it prints out the correct binary number (1010)?

Any kind of help is greatly appreciated, kind regards.

Upvotes: 1

Views: 2774

Answers (2)

YesThatIsMyName
YesThatIsMyName

Reputation: 1636

If one wants to print recursively the bits of a char with leading zeros, he may use following code:

#include <stdio.h>

void print_bit_iter(char x, int n)
{
    int bit = (x & (1 << n - 1)) != 0;
    printf("%d", bit);

    if(n != 0)
      print_bit_iter(x, n - 1);
}

int main()
{
  print_bit_iter('U', 8);
}

This will have

01010101

as the output.

Upvotes: 1

user2736738
user2736738

Reputation: 30926

The reversal is done using the call stack of the functions. By that I mean that the way the functions are called, this guarantess that the MSB will be printed first then the next one and so on.

void binary(int num)
{
    if (num == 0) return;

    binary(num / 2);  // Wait, I will print but you first print the MSB's.
    printf("%d", num % 2); // Now I print the last digit.
}

Downward motion moves the calls.

{binary(12)                     
   {binary(6)                 
      {binary(3)        
        {binary(1)  
             binary(0) -- returns
        Now we print 1
        }
      print 1
      }
   prints 0
   }
prints 0
}

Upvotes: 1

Related Questions