stack program in c++

stack program in c++ Defines as, stack is a data structure, basically, a stack is a linear data structure represented in real physical stack or pile.

In stack data structure insertion and deletion of the element is done only one end called top.  The basic implementation of the stack is LIFO(Last in First Out), which means the element which is entered first is popped out in the last.

stack program in c++

Example of stack program in c++:


#include<iostream>
using namespace std;
#define size 5
class stack
{
 int stack[size];
 int tos;
 
 public:
 void temp();
 void push();
 int pop();
 void display();
};
void stack::temp()
{
tos=0;
}
void stack::push()
{
 int i;
 if(tos==size)
 {
  cout<<"stack overflown";
  return;
 }
 cout<<"enter elementn";
 cin>>i;
 stack[tos]=i;
 tos++;
}
int stack::pop()
{
 if(tos==0) 
  {
   cout<<"stack underflown";
   return 1;
  }
  tos--;
  cout<<"popped element is"<<stack[tos]<<"t";
  return 0;
}
void stack::display()
{
 if(tos==0)
 {
  cout<<"stack emptyn";
  return;
 }
 for(int i=0;i<tos;i++)
 {
  cout<<stack[i]<<"t";
 }
}
int main()
{
int ch,i;
stack s;
s.temp();
while(1)
{
 cout<<"n 1.push n 2.pop n 3.display n 4. exitn";
 cout<<"enter the elementn";
 cin>>ch;
 switch(ch)
 {
  case 1: s.push();
  break;
  case 2: s.pop();
  break;
  case 3: s.display();
  break;
  case 4: exit(0);
  default:
  return 0;
 }
}
}

Screenshots of stack program in c++ :

stack program in c++
stack program in c++

Direct Download CPP Executable file

Download

Recommended Posts:

0 thoughts on “stack program in c++”

Leave a Comment