F How To Push Or Pops Elements From A Stack Using Array In C | CodeTheta

How To Push Or Pops Elements From A Stack Using Array In C

December 20, 2015

#include<stdio.h>
#include<conio.h>
#define MAXSTK 10
int stack[MAXSTK],top=-1,x,data,choice,item;
void push();
int pop();
void display();
void main()
{
 do
 {
 clrscr();
 printf("\n\n\n\t  :: Menu:: \n");
 printf("\n\n\t (1) Push E;ement.");
 printf("\n\n\t (2) Pop Element.");
 printf("\n\n\t (3) Exit.");
 printf("\n\n\t     Enter Your Choice. ");
 choice=getche();

 clrscr();

 switch(choice)
 {
  case '1':
  printf("\n\n\t Enter A Number :  ");
  scanf("%d",&x);
  push(stack,x);
  printf("\n\n\t The Elements Are : ");
  display(stack);
  getch();
  break;

  case '2':
  data=pop(stack);
  printf("\n\n\n\n\tThe Top Element %d Is popped...",data);
  printf("\n\n\n\n\t The Rest Elements Are : ");
  display(stack);
  getch();
  break;

  case '3':
  exit();
 }

}while(1);
}

void push(int stack[],int x)
{
 if(top==MAXSTK)
 {
  printf("\n\n\t Stack Overflow!!! \n");
  return;
 }
 else
  top=top+1;
  stack[top]=x;
}

int pop(int stack[])
{
 int item;
 if(top==-1)
 {
  printf("\n\n\n\t\t Stack Underflow!!!");
  getch();
  exit(1);
 }
 else
  item=stack[top];
  top=top-1;
  return(item);
}

void display(int stack[])
{
 int i;
 if(top==-1)
  {
   printf("Stack Is Empty");
  }
 else
  {
   for(i=top;i>=0;i--)
   printf("%d ",stack[i]);
  }
}

IDE Used To Test This Code : Turbo C

Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us.We will reply you as soon as possible.

Post a Comment