Write a C program to demonstrate the working of stack of size N using an array. The elements of the stack may assume to be of type integer or real, the operations to be supported are 1. PUSH 2. POP 3. DISPLAY. The program should print appropriate messages for STACK overflow, Under flow and empty, use separate

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define maxstk 3
int top=-1,stack[maxstk];
int isempty();
int isfull();
main()
{
void push(int);
void display();
void pop();

int choice,item;
clrscr();
while(1)
{
 printf("\n stack simulator ");
 printf("\n ---------------- ");
 printf("\n 1.push");
 printf("\n 2.display");
 printf("\n 3.pop");
 printf("\n 4.exit");
 printf("\n\n enter your choice :");
 scanf("%d",&choice);
 switch(choice)
 {
  case 1:printf("\n enter the elements to be added :");
     scanf("%d",&item);
     push(item);
     break;
  case 2:printf("enter the element to the stack :");
     display();
     break;
  case 3:pop();
     break;
  case 4:exit(1);
  default:printf("error in choice!!!");
    }
    }
  }

  void push(int item)
  {
    if(isfull())
     {
       printf("\n stack overflow ");
       return;
     }
    else
      top++;
      stack[top]=item;
   if(top==maxstk-1)
    printf("\n stack is full \n");
  }



  void display()
  {
   int i;
    if(isempty())
     {
       printf("stack is empty\n");
       return;
     }
    else
     {
       printf("\n stack elements \n");
       for(i=top;i>=0;i--)
       printf("%d\t",stack[i]);
     }
  }

  void pop()
  {
    int item;
    if(isempty())
     {
      printf("\n stack underflow");
      return;
     }
    else
     {
      item=stack[top];
      top=top-1;
      printf("\n the poped element is %d \n",item);
      if(top==-1)
      printf("\n stack is empty \n");
     }
  }
  int isempty()
  {
   if(top==-1)
   return 1;
   else
   return 0;
  }
  int isfull()
  {
   if(top==maxstk-1)
   return 1;
   else
   return 0;
  }

No comments:

Post a Comment