Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging a recursive function

Tags:

c

recursion

   #include<stdio.h>
   void binary(int n)
   {
      int bin=0;
      if(n!=0) 
      {
           bin=n%2;
           binary(n/2);
      }
      printf("%d",bin);
   }

   void main()
   {
      int a;
      printf("Decimal value: ");
      scanf("%d",&a);
      binary(a);
   }

When I tried to run above code, it outputs the binary value of the decimal number a preceding with one 0. As I have used recursive function here, it also puts the initial value of bin (i.e. 0) on stack and prints that 0 as well. But I want to display only binary values not that preceding 0.

I would be glad if anyone suggest me how to make this function not to store that initial value of bin on stack.

like image 622
Kindle Avatar asked Mar 19 '26 06:03

Kindle


1 Answers

Try this.

#include<stdio.h>
void binary(int n)
{
       bin=n%2;
       if(n/2!=0)
         binary(n/2);

  printf("%d",bin);
}
void main()
{
   int a;
   printf("Decimal value: ");
   scanf("%d",&a);
   binary(a);
}

Since it checks whether n/2 == 0 before calling binary() it never prints the intial 0.

like image 185
nedR Avatar answered Mar 21 '26 19:03

nedR