3
   #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.

3
  • this will run forever because you aren't decrementing n at all. Commented Jan 6, 2014 at 2:59
  • @FaddishWorm: he's doing n / 2 as the argument. Commented Jan 6, 2014 at 3:00
  • @FaddishWorm Nop,binary(n/2) call makes n decrementing by half. and i have used (n==0) as base condition. Commented Jan 6, 2014 at 3:01

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.