stack operations program in c programming
February 12, 2023

Stack Operations program in c Programming

In this tutorial, we are going to write a C program to perform stack operations like push, pop, and peep. before we start with the program please read about the stack.

#include<stdio.h>
#include<conio.h>
#define MAXSTK 10

struct stack
{
   int data[MAXSTK];
   int top;
};

void push(struct stack *, int);
int pop(struct stack *);
int peep(struct stack);

void main()
{
   int ch, item;
   struct stack s1;
   s1.top = -1;

   do
   {
      clrscr();
      printf("\t\t\tMAIN MENU\n");
      printf("\t\t\t********\n\n");
      printf("\t\t 1. Push in a Stack. \n");
      printf("\t\t 2. Pop from the Stack. \n");
      printf("\t\t 3. Stack Top or Peep. \n");
      printf("\t\t 4. Exit.\n\n");
      printf("\t\t Enter your choice:-");
      scanf("%d",&ch);
      clrscr();

      switch(ch)
      {
         case 1:
               printf("Enter the value which is to be Push:- ");
               scanf("%d",&item);
               push(&s1,item);
               break;
         case 2:
               item = pop(&s1);
               printf("Pop Value ==> %d",item);
               break;
         case 3:
               item = peep(s1);
               printf("Stack Top Value ==> %d", item);
               break;
         case 4:
               break;
         default:
               printf("Wrong Choice !. Try Again. ");
      }
      getch();
   }while(ch!=4);
}

void push(struct stack *p,int item)
{
   if(p->top == MAXSTK-1)
   {
      printf("Overflow.");
      return;
   }
   p->top++;
   p->data[p->top] = item;
}

int pop(struct stack *p)
{
   int item;
   if(p->top == -1)
   {
      printf("Underflow");
      return NULL;
   }
   item = p->data[p->top];
   p->top--;
   return(item);
}

int peep(struct stack s1)
{
   int item;
   if(s1.top == -1)
   {
      printf("Stack is Empty.");
      return(NULL);
   }
   item = s1.data[s1.top];
   return(item);
}