title: Decimal To Binary conversion using Array and Stack
body: <p>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:</p>
  
  <blockquote>
    <p>Number is divided and remainders are pushed in stack. 
    Remainders are popped one at a time and converted into Binary</p>
  </blockquote>
  
  <p>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.</p>
  
  <pre><code>// Decimal to Binary conversion using Stack
  #include&lt;stdio.h&gt; 
  #include&lt;math.h&gt;
  
  #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",&amp;num);
       while(num&gt;0)
       {
           if(num==1)
               push(num);
           else
           {
               x = num%2;
               push(x);
            }
           num/=2;
           flag++;
       }
  
  for(i=0;i&lt;flag;i++)
  {
      s = pop();
      bin = bin + s*pow(10,(flag-1-i));
  }
  
  printf("\nEquivalent Binary number is --&gt; %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;
    }
  </code></pre>
  
  <p>Will anybody help me by finding the logical flaw?</p>
  
  <p>Thank You</p>