CodeSeeker CodeSeeker - 1 year ago 158
C Question

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

#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: ");
x = num%2;

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");
stk[++top] = n;

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

Will anybody help me by finding the logical flaw?

Thank You

Answer Source

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)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download