c++ stack array based implementation code example

Example 1: write a program to implement stack using array

#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
   if(top>=n-1)
   cout<<"Stack Overflow"<<endl;
   else {
      top++;
      stack[top]=val;
   }
}
void pop() {
   if(top<=-1)
   cout<<"Stack Underflow"<<endl;
   else {
      cout<<"The popped element is "<< stack[top] <<endl;
      top--;
   }
}
void display() {
   if(top>=0) {
      cout<<"Stack elements are:";
      for(int i=top; i>=0; i--)
      cout<<stack[i]<<" ";
      cout<<endl;
   } else
   cout<<"Stack is empty";
}
int main() {
   int ch, val;
   cout<<"1) Push in stack"<<endl;
   cout<<"2) Pop from stack"<<endl;
   cout<<"3) Display stack"<<endl;
   cout<<"4) Exit"<<endl;
   do {
      cout<<"Enter choice: "<<endl;
      cin>>ch;
      switch(ch) {
         case 1: {
            cout<<"Enter value to be pushed:"<<endl;
            cin>>val;
            push(val);
            break;
         }
         case 2: {
            pop();
            break;
         }
         case 3: {
            display();
            break;
         }
         case 4: {
            cout<<"Exit"<<endl;
            break;
         }
         default: {
            cout<<"Invalid Choice"<<endl;
         }
      }
   }while(ch!=4);
   return 0;
}

Example 2: push pop code in c++

#include<iostream>
using namespace std;
#define Max 100
class stack{
	public:
		int top;
		int size;
		int *s;
		int stack[Max];
		
		void push()
		{
			int value;
			if(top==size-1)
			{
				cout<<"overflow";
			}
			else
			{
				cout<<"Enter value to push \n";
				cin>>value;
				top++;
				stack[top]=value;
			}
		}
		int pop()
		{
			if(top==-1)
			{
				cout<<"Underflow";
			}
			else
			{
				cout<<"Deleted value is \n"<<stack[top];
				top--;
			}
		}
		void display()
		{
			int i;
			for(i=top;i>=0;i--)
			{
				cout<<stack[i]<<endl;
			}
		}
};
int main()
{
	stack st;
	cout<<"Enter the size of the stack";
	cin>>st.size;
	st.s=new int[st.size];
	st.top=-1;
	int ch;
	while(st.size!=0)
	{	
	cout<<endl<<"    #####       STACK MENU     #####     "<<endl;
	cout<<"1. PUSH OPERATION \n2. POP OPERATION \n3. DISPLAY \n4.Exit \n";
	cin>>ch;
	switch(ch)
	{
		case 1: 
		    st.push();
		    break;
		case 2:
			st.pop();
			break;
		case 3:
			st.display();
			break;
		case 4:
			exit(0);
			
		default:cout<<"\n Choose correct option";
	}
}
return 0;
}

Tags:

C Example