0

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

DrunkOnBytes
  • 39
  • 1
  • 2
  • 6
  • What do you mean "comes one less than the actual number"? Less by 1? Less by 1 digit? In addition, the `if/else` inside the loop is completely redundant. – barak manos Nov 29 '14 at 19:04
  • Probably Overflow `bin`. try `long long bin = 0`.. `printf("..%lld", bin);` – BLUEPIXY Nov 29 '14 at 19:14
  • I tried your program which works above 3, for example `257` --> `100000001`. So the only flaw (apart from its unnecessarry complexity) might be your understanding of binary numbers. – Weather Vane Nov 29 '14 at 20:00
  • I tried it once again after your comment, it is still coming the same. For example, if I enter the decimal number as 4, it gives me 99 as answer. If I give 257, it gives me 100000000 ..!! – DrunkOnBytes Nov 30 '14 at 04:11

5 Answers5

0

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)));
Patricio Sard
  • 2,092
  • 3
  • 22
  • 52
0

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;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • How does this help the OP find the **logical flaw** in his code? – David C. Rankin Nov 29 '14 at 22:28
  • What logical flaw? If you can find it, post it yourself. My answer is that the flaw is an over-complicated solution whose "wrong" answer does not even exist, as I commented above. – Weather Vane Nov 29 '14 at 23:06
  • Your answer **does not address the other person's question** at all. It just says **"your program is unnecessarily complicated.", Here is how I do it**. It is a **Non-Answer.** – David C. Rankin Nov 30 '14 at 04:36
0
 //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);
    }
  }
0

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

Mohd Shibli
  • 950
  • 10
  • 17
0

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]);