Decimal to Binary conversion using Stack in c

 Decimal to Binary conversion using Stack in c

#include<stdio.h>
#include<conio.h>
#include<process.h>
#define MAX 10

typedef struct stack
{
 int data[MAX];
 int top;
}stack;
//---------------------
int empty(stack *s)
{
 if(s->top==-1)
      return(1);
 return(0);
}
//----------------------
int full(stack *s)
{
 if(s->top==MAX-1)
     return(1);
 return(0);
}
//-----------------------
void push(stack *s,int x)
{
 s->top=s->top+1;
 s->data[s->top]=x;
}
//-----------------------
int pop(stack *s)
{
 int x;
 x=s->data[s->top];
 s->top=s->top-1;
 return(x);
}
//------------------------
void main()
{
 stack s;
 int num;

 s.top=-1;
     printf("\nEnter decimal number:");
     scanf("%d",&num);

     while((num!=0))
     {
       if(!full(&s))
          {
          push(&s,num%2);
          num=num/2;
          }
       else
          {
          printf("\nStack overflow");
          exit(0);
          }
     }

    printf("\n");
    while(!empty(&s))
       {
       num=pop(&s);
       printf("%d",num);
       }
}
 
 
 
 Explanation :
Step 1:s.top=-1;
  • Initially Top = -1 .
  • It is used to create empty Stack.
Step 2 :
printf("nEnter decimal number:");scanf("%d",&num);
  • Accept Decimal Number using Scanf
Step 3:
As per video , Now we are dividing the original number by 2 and remainder is pushed onto stack , In the Second Iteration again we are dividing num by 2 and remainder is pushed onto stack . This action is carried out till number becomes 0.
Step 4 :
if(!full(&s)) { push(&s,num%2); num=num/2; }
  • Push Remainder Onto Stack if Stack is not Full and number != 0
When number becomes 0 i.e Do not push elements onto stack. Now as shown in video after pushing pop all remainders one by one display it .
 Above is the example to convert Decimal to Binary conversion using 
Stack using c

Comments

Popular posts from this blog

Drawing National flag using Java Applet

CELog and Kernel Tracker

WinCE Essentials Volume and File Control