DS Program1 Stack Array
DS Program1 Stack Array
Program 1
Array Implementation of Stack
🎯 What will you learn? By the end of this session you will understand: what a Stack is and
how it works in real life, how an array stores stack elements in memory, what
Push/Pop/Peek/Display operations do, how each line of the C++ code works, and how to write
your own stack program from scratch.
SECTION 1 — WHAT IS A STACK?
🎯 Real-Life Analogy: Imagine a stack of plates in a mess/canteen. You can only add a plate
on TOP. You can only remove a plate from TOP. You cannot take a plate from the middle! This
is EXACTLY how a Stack data structure works in a computer.
LIFO = Last In, First Out → The LAST element added is the FIRST one to be removed.
top=3
PUSH Add a new element on top of Put a new plate on top of Stack is FULL (Overflow)
the stack the pile
POP Remove the top element from Take the top plate off the Stack is EMPTY
the stack pile (Underflow)
PEEK See the top element WITHOUT Look at the top plate Stack is EMPTY
removing it without lifting it
DISPLAY Show all elements from top to Count all plates from top Stack is EMPTY (nothing
bottom to bottom to show)
An array is like a row of boxes in memory. Each box has an index (0, 1, 2...). We use a variable called top
to remember WHICH box currently holds the topmost element.
💡 Key Insight: top = 3 means stack[3] = 40 is the topmost element. top = -1 means the stack
is empty (no elements). top = size-1 means the stack is full (overflow if you try to push).
SECTION 2 — FULL CODE WALKTHROUGH (LINE BY LINE)
📖 How to Read This Section: LEFT side = the actual C++ code (exactly as you write it).
RIGHT side = a plain English explanation of what that line does and WHY it is written that way.
Read left and right together — like reading subtitles on a movie!
🏫 What is a Class? A class is a blueprint — like a blueprint for building a house. The blueprint
is not the house itself; it just describes how to build one. Similarly, 'class Stack' is the blueprint
for a Stack. When we write Stack s; in main(), we are BUILDING one actual stack from that
blueprint.
stack[100] in memory after user enters size=5 and pushes 10, 20, 30
10 20 30
cout << "Enter Stack Size 🎤 Ask the user how big they want the stack.
: ";
cin >> size; cout prints the question on screen. cin reads the
user's answer and stores it in size.
Example: User types 5. Now size = 5. The stack
can hold at most 5 elements.
This makes our code flexible — different users can
choose different sizes.
🍽️ push() = Putting a new plate on top of the stack Before placing the plate, we first
CHECK: Is the stack already full? If yes → refuse (Stack Overflow). If no → place the element
and move top up by 1.
cout << "Enter Element 🔁 The SAME push logic, inside the loop.
" << i << ": ";
cin >> value; Prints: 'Enter Element 1:', 'Enter Element 2:' etc.
stack[++top] = value; (uses i to number them)
Reads each value and pushes it using stack[++top]
= value — same as single push()
After the loop finishes: 'Elements inserted successfully.'
is printed.
🍽️ pop() = Removing the top plate Before removing, we CHECK: Is the stack empty? If yes
→ refuse (Stack Underflow). If no → print the top element and reduce top by 1.
cout << "Deleted Element : ⭐ THE HEART OF POP — most important line!
"
<< stack[top--] << stack[top--] means: FIRST use the current top index
endl; to get the value, THEN decrease top by 1.
Why top-- (post-decrement)? Because we want to
PRINT the value at top FIRST, then reduce top.
Example: top=3, stack[3]=40 → prints 40, then top
becomes 2
endl flushes the output and moves to next line (similar to
\n but safer).
for(int i=1; i<=n && top 🔄 Loop runs n times BUT ALSO checks top != -1
!= -1; i++)
each time.
{
cout << "Deleted: " << The condition i<=n && top != -1 has TWO parts
stack[top--]; joined by &&:
} • i <= n → don't pop more than n times
• top != -1 → don't pop if already empty (safety
net!)
Example: user wants 5 pops but only 3 elements remain
→ pops 3 and stops safely.
void peek() 👁️ peek() lets you SEE the top without removing
{ it.
if(top == -1)
{ cout << "Stack is
First check: if empty, tell the user and exit. Can't
Empty.\n"; return; } show top of an empty stack!
cout << "Top Element : " 🔍 stack[top] — Read the value at index top
<< stack[top] << WITHOUT changing top.
endl;
IMPORTANT: We use stack[top] NOT stack[top--]!
stack[top] → Just READS the value. top stays
unchanged.
stack[top--] → READS and then DECREMENTS
top (that's pop, not peek!)
Example: top=3, stack[3]=40 → prints '40'. top is still 3
after peek.
🚀 main() is where your program STARTS running. Every C++ program must have exactly
one main() function. When you run the program, the computer jumps directly to main() and starts
executing from there.
int choice; 🔄 do-while loop keeps the menu running until the
do user exits.
{
int choice — stores which menu option the user
picks (1–7).
do { ... } while(condition) — runs the block FIRST,
then checks the condition.
Key difference from while: do-while ALWAYS runs at
least once — the menu must show at least once.
cout << "\n===== Stack 🖨️ Print the menu options and read user's choice.
Menu =====\n";
cout << "1. Push\n"; \n at the start prints a blank line (spacing for
// ... (all menu options) readability)
cout << "\nEnter Choice: Each cout prints one menu option. All 7 options
"; (Push, Pop, Peek... Exit) are shown.
cin >> choice; cin >> choice reads which number the user typed (1 to
7).
User
Stack s switch:
Start enters Show Read choice==7?
main() → Constructor → stack → Menu → choice → call → Exit / Loop
runs function
size
SECTION 3 — SAMPLE RUN (What You See on Screen)
top Tracks which index holds the TOP element. Starts int top = -1
at -1 (empty)
size Maximum number of elements the stack can hold cin >> size (in
constructor)
Stack Overflow Trying to push when stack is full (top == size-1) if(top==size-1) in push()
Stack Underflow Trying to pop/peek when stack is empty (top == -1) if(top==-1) in pop()
push: ++top Increment top FIRST, then store at that index stack[++top] = value
pop: top-- Read value at top FIRST, then decrement top stack[top--]
peek: top (no Read value at top WITHOUT changing top stack[top]
change)
do-while Menu always shows at least once; repeats until exit do{...}while(choice!=7)
private / public private = hidden internals. public = usable from class members
outside
Stack Overflow Program prints 'Stack top == size-1 (array Check array full
Overflow!' and stops full) before pushing
push
Using top++ instead of Wrong index used Post-increment Always use ++top
++top in push (stores at OLD top, not returns value (pre-increment) for
new top) BEFORE push
incrementing
Using --top instead of top-- Deletes wrong element Pre-decrement Always use top--
in pop changes top first (post-decrement)
for pop
Error What Happens Why It Happens How to Fix
Missing break; in switch Multiple cases execute switch falls through to Add break; at end
unintentionally (fall- next case without of every case
through) break
Forgetting return; after Code continues after No early exit from Always add return;
overflow/underflow printing error function after error
message messages
Browser Back Pages visited are pushed onto a stack. You visit Page A, B, C. Press Back → C
Button Back button pops the stack. removed, B shown. Press Back → B
removed, A shown.
Undo/Redo in Every action (typing, deleting) is pushed. You type 'Hello', then delete 'o'. Press
editors Ctrl+Z pops the last action. Ctrl+Z → 'o' is restored (last action
undone).
Function Call When function A calls function B, B is main() calls push(), push() runs, returns →
Stack pushed. When B returns, B is popped main() continues. This uses the CPU's call
and A resumes. stack.
⚡ The 10 Things You MUST Remember: 1. Stack = LIFO (Last In First Out). 2. top starts at -
1 (empty). top = size-1 means full. 3. push: check overflow FIRST → stack[++top] = value. 4.
pop: check underflow FIRST → cout << stack[top--]. 5. peek: check empty FIRST → cout <<
stack[top] (NO decrement!). 6. display: loop from top DOWN to 0. 7. ++top (pre) for push. top--
(post) for pop. 8. break; is mandatory in every switch-case. 9. private = hidden. public =
accessible from main(). 10. do-while ensures the menu runs at least once.
🐢 Slow What does 'Stack Overflow' The stack is full. We tried to push when top == size-1.
Learner mean? The program prints 'Stack Overflow!' and stops.
🐢 Slow What is the initial value of top and top = -1. Because no element is present yet. -1 is below
Learner why? all valid indices (0,1,2...).
📚 What is the difference between pop() removes the top element (top--). peek() only
Average pop() and peek()? READS the top element (top unchanged). Both check if
empty first.
📚 Why do we use ++top in push but push: increment first, then store (pre-increment = right
Average top-- in pop? slot). pop: print current top first, then reduce (post-
decrement = right value).
🏆 Topper What happens if we remove After executing case 1 (push), execution will fall through
break; from case 1 in switch? and also execute case 2 (pushMultiple) without user
asking — a bug called switch fall-through.
🏆 Topper How would you modify this code Push each character of the string onto the stack. Pop all
to implement a 'Reverse a String' characters and print them — they come out in reverse
feature using Stack? order (LIFO property).
Add a function isFull() that returns true if stack return (top == size - 1); 🐢 Easy
is full
Add a function isEmpty() that returns true if return (top == -1); 🐢 Easy
stack is empty
Add a function count() that returns the number return (top + 1); — because top is 📚
of elements 0-indexed Medium
Modify display() to also print index numbers Print i alongside stack[i] in the for 📚
beside each element loop Medium
Add a function search(int x) to find if element x Loop through stack[0] to stack[top] 🏆 Hard
is in stack and compare
Challenge Hint Difficulty
Use this stack to reverse a string input by the Push each char, then pop all to get 🏆 Hard
user reverse
✅ You are ready for the Lab when you can: 1. Write the full Stack class from memory
(without looking). 2. Explain what every single line does in plain English. 3. Draw the stack state
after each push and pop operation. 4. Spot and fix overflow/underflow errors instantly. 5.
Answer all three levels of revision questions above.