CodeSeeker CodeSeeker - 2 months ago 8
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
#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

Answer

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