Q9) Write A Program in C++ For Stack and Its Applications
Q9) Write A Program in C++ For Stack and Its Applications
Description:
A Stack is a linear data structure that holds a linear, ordered sequence of elements. It is an
abstract data type. A Stack works on the LIFO process (Last In First Out), i.e., the element
that was inserted last will be removed first. To implement the Stack, it is required to maintain
a pointer to the top of the Stack, which is the last element to be inserted because we can
access the elements only on the top of the Stack.
Operation on Stack:
1. PUSH: PUSH operation implies the insertion of a new element into a Stack. A new
element is always inserted from the topmost position of the Stack; thus, we always need to
check if the top is empty or not, i.e., TOP=Max-1 if this condition goes false, it means the
Stack is full, and no more elements can be inserted, and even if we try to insert the element, a
Stack overflow message will be displayed.
Algorithm:
Print “Overflow”
Goto Step 4
Step-4: END
2. POP: POP means to delete an element from the Stack. Before deleting an element, make
sure to check if the Stack Top is NULL, i.e., TOP=NULL. If this condition goes true, it
means the Stack is empty, and no deletion operation can be performed, and even if we try to
delete, then the Stack underflow message will be generated.
Algorithm:
Print “Underflow”
Goto Step 4
Step-4: END
3. PEEK: When we need to return the value of the topmost element of the Stack without
deleting it from the Stack, the Peek operation is used. This operation first checks if the Stack
is empty, i.e., TOP = NULL; if it is so, then an appropriate message will display, else the
value will return.
Algorithm:
Goto Step 3
Step-3: END
Syntax:
Program Code:
#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;
}
Output: