'Decimal To Binary conversion using Array and Stack

This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:

Number is divided and remainders are pushed in stack. Remainders are popped one at a time and converted into Binary

The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.

// Decimal to Binary conversion using Stack
#include<stdio.h> 
#include<math.h>

#define max 20

int top=-1, stk[max];
void push(int);
int pop(void);

int main() 
{
     int i,num,x,flag=0,s, bin=0, factor;
     printf("Enter any decimal number: ");
     scanf("%d",&num);
     while(num>0)
     {
         if(num==1)
             push(num);
         else
         {
             x = num%2;
             push(x);
          }
         num/=2;
         flag++;
     }

for(i=0;i<flag;i++)
{
    s = pop();
    bin = bin + s*pow(10,(flag-1-i));
}

printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}

void push(int n)
{
     if(top == max-1)
     {
          printf("Error! Overflow");
          return;
     }
     stk[++top] = n;
 }

 int pop(void)
 {
     int y;
     if(top == -1)
     {
          printf("Error! Underflow");
          return;
     }
     y = stk[top];
     top = top-1;
     return y;
  }

Will anybody help me by finding the logical flaw?

Thank You



Solution 1:[1]

My answer is your program is unnecessarily complicated.

#include<stdio.h> 

int main() 
{
    unsigned num, i, zeros = 0;
    printf("Enter a decimal number: ");
    scanf("%u", &num);
    printf ("Decimal %u in binary is ", num);
    for (i=sizeof(unsigned)*8; i>0; i--)
    {
        if ((int)num < 0)           // get MSB
            zeros = printf ("1");   // cancel 0-suppresion
        else if (zeros)
            printf ("0");
        num <<= 1;
    }
    printf ("\n");
    return 0;
}

Solution 2:[2]

The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.

bin = bin + ceil(s*pow(10,(flag-1-i)));

Solution 3:[3]

 //C Program to convert Decimal to binary using Stack

 #include<stdio.h>

 #define max 100

 int stack[max],top=-1,i,x;

         /*------ Function Prototype------------*/
  void push (int x)
  {
    ++top;
    stack [top] = x;

   }
  int pop ()
   {
    return stack[top];

   }

          /*-------------------------------------*/
  void  main()
  {
    int num, total = 0,item;
    printf( "Please enter a decimal: ");
    scanf("%d",&num);

    while(num > 0)
     {
       total = num % 2;
       push(total);
       num /= 2;
     }

    for(i=top;top>-1;top--)
    {
     item = pop ();
     printf("%d",item);
    }
  }

Solution 4:[4]

Here is a simpler version of your above program

    int main(){
    int n,remainder;
    printf("Enter a decimal number:");
    scanf("%d",&n);
    while(n!=0){
        remainder = n%2;
        n = n/2;
        push(remainder); // inserting in stack
    }
    display(); // displaying the stack elements
}

reference of above code C program to Convert Decimal number into Binary using Stack

Solution 5:[5]

So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.

So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:

  1. You're indexing an array with an int that you initialize to -1
  • This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes

  • What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:

    unsigned int top = 0;

and changing where you access top from:

 stk[++top] = n;

to

 stk[top++] = n;

You will also have to change

 y = stk[top];
 top = top-1;

to

 top = top-1;
 y = stk[top];

I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.

PRINTF("%d%d%d",stk[2],stk[1],stk[0]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Veena.Kalaskar
Solution 4 Mohd Shibli
Solution 5 Mike Stallone