DEFINITION OF STACK:
A stack is a linear data structure that follows the Last In First Out (LIFO) principle.
That means the last element added to the stack is the first one to be removed.
Real-world examples of LIFO
Consider a stack of plates. When we add a plate, we add at the top. When we remove, we
remove from the top.
A shuttlecock box (or any other box that is closed from one end) is another great real-world
example of the LIFO (Last In, First Out) principle where do insertions and removals from the
same end.
Explanation:
• Think of a stack like a pile of plates—you add a plate on top and remove from the
top.
• Operations:
o push() → to insert an element
o pop() → to remove the top element
o peek()/top() → to get the top element without removing it
o isEmpty() → to check if the stack is empty
• In C++, a stack can be implemented using arrays, linked lists, or by using the STL
stack container.
Basic Syntax (Using Array):
#define SIZE 100
int stack[SIZE];
int top = -1;
// Push
void push(int value) {
if(top == SIZE - 1)
cout << "Stack Overflow";
else
stack[++top] = value;
}
// Pop
void pop() {
if(top == -1)
cout << "Stack Underflow";
else
top--;
}
// Peek
int peek() {
if(top == -1)
return -1;
return stack[top];
}
What is Stack ?
Representation of Stack:
PUSH OPERATION IN STACK
POP OPERATION IN STACK
TOP OR PEEK OPERATION IN STACK
EMPTY STACK OPERATION
C++ STACK PROGRAM USING ARRAY
#include <iostream>
using namespace std;
#define SIZE 5
class Stack
{
int stack[SIZE];
int top;
public:
Stack()
{
top = -1;
}
void push(int value)
{
if (top == SIZE - 1)
{
cout << "Stack Overflow\n";
}
else
{
stack[++top] = value;
cout << value << " pushed to stack\n";
}
}
void pop()
{
if (top == -1)
{
cout << "Stack Underflow\n";
}
else
{
cout << stack[top--] << " popped from stack\n";
}
}
void display() {
if (top == -1) {
cout << "Stack is empty\n";
}
else
{
cout << "Stack elements: ";
for (int i = top; i >= 0; i--)
{
cout << stack[i] << " ";
}
cout << endl;
}
}
};
int main()
{
Stack s;
s.push(10);
s.push(20);
s.push(30);
s.display();
s.pop();
s.display();
return 0;
}
Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
Stack elements: 30 20 10
30 popped from stack
Stack elements: 20 10
Simple Program:
#include <iostream>
using namespace std;
#define SIZE 5
class Stack
{
int arr[SIZE], top = -1;
public:
void push(int val)
{
if (top == SIZE - 1) cout << "Overflow\n";
else arr[++top] = val;
}
void pop()
{
if (top == -1) cout << "Underflow\n";
else cout << "Popped: " << arr[top--] << endl;
}
void display()
{
for (int i = top; i >= 0; i--) cout << arr[i] << " ";
cout << endl;
}
};
int main()
{
Stack s;
s.push(10);
s.push(20);
s.display();
s.pop();
s.display();
return 0;
}