STACKS (using arrays)
STACKS
A Stack is a LIFO (Last in First Out) Structure.
Lets take a day to day life example to understand Stacks
Now Your Mother Prepares Roti and she is going to store it in a container before serving it to you. The Container is only has one opening at the top. so she prepares a roti and keeps it in the container and for example she has prepared 4 Rotis. Now she Brings the container and gives it to you. You would take the 4th Roti which is at the Top. So You are taking the roti which was made last as your first roti.
Thats exactly how stacks work. There is only one Opening and Data are added and removed from the same end.
Adding Data in Stack is Known as PUSH and removing data is Known as POP. There is only one opening in stack and is called as TOP.
#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;
}
here Stack overflow means Maximum number of elements have been reached and stack underflow means there are no elements left out in the stack to be removed.
21
