C Program to Perform Array Implementation of Stack ADT

0
492

C Program to Perform Array Implementation of Stack ADT

CONSTRUCTION:

  1. Define the stack structure, read the size of stack and choice of operation to be performed.
  1. Push:
  • Read the element, ‘x’ to be inserted.
  • Check whether ‘top’ is equal to ‘size-1’, if so print “stack is full”.
  • Else, increment the ‘top’ & place the element ‘x’ at the ‘top’.
  1. Pop:
  • If ‘top’ position is equal to ‘-1’ then print “stack is empty”.
  • Else, delete the element in ‘top’ position.
  • Decrement the ‘top’ position.
  1. Display:
  • If the stack is empty then print the message “stack is empty”
  • Else, display all elements in the stack.
  1. Isempty:
  • If ‘top’ position is equal to ‘-1’ then print “stack is empty”.
  • Else, print “stack is not empty”.
  1. Isfull:
  • Check whether ‘top’ is equal to ‘size-1’, if so print “stack is full”.
  • Else, print “stack is not full”.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<process.h>
struct stack
{
 int item[10],size;
 int top;
}s;
void push(int);
int pop();
void disp();
int isempty();
int isfull();
void main()
{
 int ch,x;
 s.top=-1; 
 printf("Enter stack size\t");
 scanf("%d",&s.size);
 while(1)
 {
 printf("1.Push\n2.Pop\n3.Display\n4.Isempty\n5.Isfull\n6.Exit\nEnter ur choice\n");
 scanf("%d",&ch);
 switch(ch)
 { case 1:
 printf("Enter the element to push");
 scanf("%d",&x);
 push(x);
 break;
 case 2:
 x=pop();
 break;
 case 3:
 disp();
 break;
 case 4:
 if(isempty())
 printf("Stack is empty");
 else
 printf("Stack is not empty");
 break;
 case 5:
 if(isfull())
 printf("Stack is full");
 else
 printf("Stack is not full");
 break; 
case 6:
 exit(0); 
 } }
 getch();}
void push(int x)
{
 if(isfull())
 printf("stack is full\n");
 else
 {
 s.top++;
 s.item[s.top]=x;
 }
 }
 int pop()
 { int x;
 if(isempty())
 printf("Stack is empty");
 else
 { x=s.item[s.top];
 s.top--;
 printf(“the poped element is = %d”,x);
 } }
 void disp()
 { int i;
 if(isempty())
 printf("Stack is empty\n");
 else
 {
 printf("Stack contents are\n");
 for(i=0;i<=s.top;i++) 
 printf("%d\t",s.item[i]);
 }
 }
 int isempty()
 { if(s.top==-1)
 return(1);
 else
 return(0);
 }
 int isfull()
 { 
 if(s.top==s.size-1) 
 return(1);
 else
 return(0);
}

Leave a Reply