C program to implement Stack

C program to do operations on Stack using Array

Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
  • Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
  • Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Applications of stack:
  • Balancing of symbols
  • Infix to Postfix /Prefix conversion
  • Redo-undo features at many places like editors, photoshop.
  • Forward and backward feature in web browsers
  • Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
  • Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and sudoku solver.
Let us check the code :)


#include <stdio.h> 
#include <conio.h>
void push();
void pop();
void peep();
void display();
void change();
void exit();
int s[100],i,loc,val,top,n,ch,y;
void main()
{
 clrscr();
 printf("Enter the value of size of array: ");
 scanf("%d",&n);

 while(1)
 {
  printf("\n1.)Push   2.)Pop   3.)Peep   4.)Change   5.)Display   6.)Exit");
  printf("\nEnter your choice:");
  scanf("%d",&ch);
  switch(ch)
  {
  case 1:
   push();
   break;
  case 2:
   pop();
   break;
  case 3:
   peep();
   break;
  case 4:
   change();
   break;
  case 5:
   display();
   break;
  case 6:
   exit(0);
  default:
   printf("\nEnter the valid choice.");
  }
 }

}

void push()
{
 if(top>=n)
 {
  printf("Stack is full.");
 }
 else
 {
  top++;
  printf("Enter your value:");
  scanf("%d",&val);
  s[top]=val;
 }
}

void pop()
{
 if(top<=-1)
 {
  printf("Stack is empty.");
 }
 else
 {
  printf("Delete Element: %d\n",s[top]);
  top--;
 }
}

void peep()
{
 printf("Enter the index of value to be display: ");
 scanf("%d",&loc);
 if((top-loc)+1<=-1 || (top-loc)>=4)
 {
  printf("\nEnter the valid index");
 }
 else
 {
  printf("\nValue at index %d : %d",loc,s[loc]);
 }
}

void change()
{
 printf("Enter index that you want to change:");
 scanf("%d",&loc);
 if((top-loc)+1<=-1)
 {
  printf("Invalid index\n");
 }
 else
 {
  printf("Enter a value you want to change:");
  scanf("%d",&val);
  s[loc]=val;
  display();
 }
}
void display()
{
 printf("\nElements are:");
 for(i=1;i<=top;i++)
 {
  printf("  %d",s[i]);
 }
 printf("\n");
}









Happy Coding :)

Comments

Popular posts from this blog

MultiSelection of Item in Recycler View

Upload Image From Android To Php Server

Merge Sort