Wednesday, 20 August 2014

Filled Under:

C program to implement various operation on stack

Share

Using the concept of stack in c we can implement a logical structure of data where data can store, access and delete.  Stack follow the LIFO (Last In First Out) mechanism  to perform various operation. It involves various operations such as push,pop,stack empty,stack full and display.

C program to implement various operation on stack

#include<stdio.h>
#define SIZE 5        
int s[SIZE], top = -1;
// Inset operation
 push(int elem) 
{ 
 if (Sfull())
 printf("nn Overflow!!!!nn");
 else 
 {
  ++top;
  s[top] = elem;
 }
}
// delete operation
int pop() 
{ 
  int elem;
  if (Sempty()) 
  {
  printf("nnUnderflow!!!!nn");
  return (-1);
  } 
  else 
  {
  elem = s[top];
  top--;
  return (elem);
  }
}
int Sfull() 
{ 
 if (top == SIZE - 1)
 return 1;
 return 0;
}
int Sempty() 
{ 
 if (top == -1)
 return 1;
 return 0;
}
display() 
{ 
 int i;
 if (Sempty())
 printf(" n Empty Stackn");
 else 
 {
  for (i = 0; i <= top; i++)
  printf("%dn", s[i]);
  printf("^Top");
 }
}
main() 
{ 
 int opn, elem;
 do 
 {
  clrscr();
  printf("n ### Stack Operations ### nn");
  printf("n Press 1-Push, 2-Pop,3-Display,4-Exitn");
  printf("n Your option ? ");
  scanf("%d", &opn);
  switch (opn) 
  {
   case 1:
   printf("nnRead the element to be pushed ?");
   scanf("%d", &elem);
   push(elem);
   break;
   
   case 2:
   elem = pop();
   if (elem != -1)
   printf("nnPopped Element is %d n", elem);
   break;
   case 3:
   printf("nnStatus of Stacknn");
   display();
   break;
   case 4:
   printf("nn Terminating nn");
   break;
   default:
   printf("nnInvalid Option !!! Try Again !! nn");
   break;
  }
   printf("nnnn  Press a Key to Continue . . . ");
   getch();
 }while (opn != 4);
}