Computer Concept & Programming In C - Unit IV - 21

/* Q.30 Write a C program to convert a given decimal number to binary number using stack */                                                                     (AKTU. 2008-09)
Ans.
/* A stack is a LIFO i.e Last In- First out
   data structure and its basic operations
   are PUSH and POP.                        */

/* Only an element can be inserted at the
   Top Of Stack (TOS) also called PUSHED
   onto the stack                           */

/* Only an element can be removed from the
   Top Of Stack (TOS) also called POPED
   from the stack                           */

/* Thus we first need to implement
   the stack. Static Implementation using
   arrays.                                  */

#include<stdio.h>
#include<conio.h>

/* We take 64 as stack size so as to
   convert the number of longest
   precision long to binary.
   Remember: the size of long is 64 bits    */
#define size 64

/* Array to hold stack */
int stack[size];

/* Top of stack    */
int tos = -1;

/* Prototypes of push and pop functions   */
void push(int);
int pop(void);

void main()
{
  int d;
  long decimal;
  clrscr();

  /* Taking input from the user  */

  printf("\nEnter any decimal number to be converted to binary");
  printf("\nDecimal Number = ");
  scanf("%ld",&decimal);

  /* Converting the decimal to binary number */

  while((decimal/2) > 0)
  {
    push((int)(decimal % 2));
    decimal /= 2;
  }
    push((int)(decimal % 2));
  /* Printing the output of binary number */
  printf("\n The number in the binary is = ");
  do
    {
       d = pop();
      if( d!= -1)
printf("%d",d);
     }
    while(d != -1);

  printf("\nPress any key to exit.");
  getch();
}
void push(int item)
{
  /* check if stack is not overflow */
  if(tos < (size - 1))
    {
       tos++;
       stack[tos] = item;
    }
   else
      printf("\n Stack is overflow ");
}
int pop(void)
{
  int item;
  /* check if stack is not underflow */
  if(tos > -1)
    {
       item  = stack[tos];
       tos--;
    }
   else
     {
       /* printf("\n Stack underflow"); */
       return -1;
     }
  return item;
}