UNIT 2 • MODULE 1 • LESSON 02
Picture a spring-loaded stack of trays in a school canteen. When a clean tray is placed on the pile, it goes on top. When the next student takes a tray, they take the one on top — the very tray that was placed there last. You never pull a tray out from the bottom or the middle while others sit on it.
In Computer Science, a stack works by that exact rule: Last-In, First-Out (LIFO). Every addition and every removal happens at one end, called the top. In Lesson 01 you saw what an ADT is in general; now you will master the stack ADT in detail — how it differs from other ADTs, how its operations work on diagrams and in pseudocode, and how those algorithms translate into C. (In Lesson 03 you will build a complete reusable array-based stack library in C.)
What you will learn
- The LIFO rule, and how a stack differs from a queue, a linked list and a plain array.
- The four core stack operations named in the syllabus — Push, Pop, Empty and Full — plus Peek.
- What stack overflow and stack underflow are, and how preconditions prevent them.
- How to trace stack diagrams and dry-run Push/Pop sequences by hand.
- Pseudocode algorithms for Push, Pop, Empty, Full and Peek under 0-based and 1-based conventions.
- Real-world computing uses of stacks, including reversing data and checking palindromes in C.
Part 1: Defining the stack ADT (LIFO)
A stack is a linear Abstract Data Type in which elements can only be added or removed at one end, known as the top. Because the most recently added item is always at the top, it is always the first item to come off. This rule is called LIFO: Last-In, First-Out (sometimes also described as FILO: First-In, Last-Out, which says the same thing from the first item’s point of view).
How does a stack differ from the other ADTs in this module?
| ADT | Order rule | Where items enter | Where items leave |
| Stack | LIFO (Last In, First Out) | Top | Top (same end) |
| Queue | FIFO (First In, First Out) | Rear (back) | Front (opposite end) |
| Circular queue | FIFO in a fixed ring | Rear (wraps around) | Front (wraps around) |
| Singly linked list | Ordered chain of nodes | Front, end or middle via links | Front, end or middle via links |
A plain array lets you read or change a[2] directly at any time. A stack deliberately forbids that: you may only touch the item currently at the top. That restriction is a feature, not a flaw — whenever a problem needs things undone or visited in reverse order, LIFO guarantees the right order automatically.
Look closely at the indicator variable top in the diagram. In C, array indexes start at 0, so the first element sits at stack[0]. Before any element is pushed, there is nothing at index 0, so we initialise top = -1. When the stack holds one item, top = 0. In a stack of capacity MAX (slots 0 to MAX - 1), the stack is full when top = MAX - 1.
Watch out for 1-based diagrams: some textbooks and exam questions number slots from 1 to MAX instead of 0 to MAX - 1. In that 1-based convention, an empty stack has top = 0 and a full stack has top = MAX. Always check which index the question starts at before tracing!
Part 2: The stack operations — Push, Pop, Empty, Full and Peek
The syllabus highlights four essential stack operations, and programmers often add a fifth helper called Peek (or Top):
| Operation | Purpose | Precondition / safety check | Effect on top (0-based) |
| Empty (isEmpty) | Returns TRUE if the stack has no items, FALSE otherwise | None | Checks top == -1 |
| Full (isFull) | Returns TRUE if the stack has no free slots left, FALSE otherwise | None | Checks top == MAX – 1 |
| Push(item) | Adds item onto the top of the stack | Check NOT Full first (else overflow) | Increases top by 1, then sets stack[top] = item |
| Pop() | Removes and returns the top item | Check NOT Empty first (else underflow) | Reads stack[top], then decreases top by 1 |
| Peek() / Top() | Returns the top item without removing it | Check NOT Empty first | Reads stack[top]; top does not change |
Overflow and underflow
- Stack overflow: trying to Push onto a stack that is already Full. In a fixed-size array, pushing without checking would write past the end of the array and corrupt other variables or crash the program.
- Stack underflow: trying to Pop (or Peek) from a stack that is Empty. Without checking first, the program would read
stack[-1], which is outside the array!
Notice the subtle order inside Push and Pop. In Push, you increment top first, then write stack[top] (so the first push moves top from -1 to 0 and writes stack[0]). In Pop, you read stack[top] first, then decrement top. Reversing either pair is one of the classic off-by-one bugs!
Try it 1Stack animator: Push, Pop and Peek
Experiment with a stack of capacity 5 (slots 0 to 4). Complete the four challenges below and watch how top, isEmpty and isFull respond.
Part 3: Stack algorithms and diagrams
Before writing C, write out the algorithms clearly in pseudocode using the 0-based convention (MAX slots, indexed 0 to MAX - 1).
PROCEDURE initStack()
top ← -1
END PROCEDURE
FUNCTION isEmpty()
RETURN top = -1
END FUNCTION
FUNCTION isFull()
RETURN top = MAX - 1
END FUNCTION
PROCEDURE push(item)
IF isFull() THEN
OUTPUT "Stack Overflow"
ELSE
top ← top + 1
stack[top] ← item
ENDIF
END PROCEDURE
FUNCTION pop()
IF isEmpty() THEN
OUTPUT "Stack Underflow"
RETURN -1
ELSE
item ← stack[top]
top ← top - 1
RETURN item
ENDIF
END FUNCTION
Tracing stack diagrams by hand
In exam questions, you are often given a list of operations and asked to draw the stack or state top at the end. Keep a small table with each step, the value of top, and the active contents from bottom (0) to top. Suppose MAX = 4 and we start empty (top = -1):
| Step | Operation | top | Active stack (bottom → top) | Note / output |
| Start | Initialise | -1 | (empty) | isEmpty is TRUE |
| 1 | Push(“A”) | 0 | A | top moves -1 → 0 |
| 2 | Push(“B”) | 1 | A, B | B sits above A |
| 3 | Pop() | 0 | A | Returns “B”; slot [1] ignored |
| 4 | Push(“C”) | 1 | A, C | Overwrites slot [1] with C |
| 5 | Push(“D”) | 2 | A, C, D | D is now at the top |
| 6 | Peek() | 2 | A, C, D | Returns “D”; top stays 2 |
Notice Step 3 and Step 4. After popping "B", "B" did not vanish by magic in RAM — top simply moved down to 0, so "B" is outside the active stack. When Step 4 pushes "C", slot 1 is overwritten cleanly. Now trace two short programs step by step.
Try it 2Trace stack algorithms
Step through a Push/Pop sequence and a word-reversing algorithm. Predict what happens before revealing the next state.
Output
0-based vs 1-based stack conventions
Because pseudocode and exam questions sometimes start array slots at 1 rather than 0, compare both conventions side by side so neither one trips you up:
| Condition or step | 0-based (slots 0 to MAX - 1) | 1-based (slots 1 to MAX) |
| Initialise (empty) | top = -1 | top = 0 |
| isEmpty() | top == -1 | top == 0 |
| isFull() | top == MAX - 1 | top == MAX |
| First Push goes to | stack[0] (top becomes 0) | stack[1] (top becomes 1) |
| Number of items stored | top + 1 | top |
Notice that in both conventions the logic of Push and Pop is identical: Push checks Full, increments top, then writes stack[top]; Pop checks Empty, reads stack[top], then decrements top. Only the boundary numbers (-1 and MAX - 1 versus 0 and MAX) change.
Example algorithm: checking balanced brackets
A classic exam-style algorithm uses a stack to check whether an arithmetic expression such as (a + (b * c)) has balanced brackets. Read the expression one character at a time. Whenever you meet an opening bracket (, Push it onto the stack. Whenever you meet a closing bracket ), first check isEmpty(): if the stack is already empty, there is an unmatched closing bracket, so return FALSE immediately; otherwise Pop one (. When you reach the end of the expression, return isEmpty(): if any ( is still left on the stack, it was never closed!
Part 4: Seeing the algorithms in C
Lesson 03 will build a full menu-driven stack struct and multiple stacks in C. Here are two short C programs so you can see today’s pseudocode algorithms running right away.
Worked example 1: Push, Pop, Overflow and Underflow in C
#include <stdio.h>
#define MAX 4
int stack[MAX];
int top = -1;
int isEmpty(void)
{
return top == -1;
}
int isFull(void)
{
return top == MAX - 1;
}
void push(int item)
{
if (isFull()) {
printf("Overflow: %d dropped\n",
item);
return;
}
top++;
stack[top] = item;
printf("Pushed %d (top=%d)\n",
item, top);
}
int pop(void)
{
int val;
if (isEmpty()) {
printf("Underflow: stack empty\n");
return -1;
}
val = stack[top];
top--;
printf("Popped %d (top=%d)\n",
val, top);
return val;
}
int main(void)
{
pop();
push(10);
push(20);
push(30);
push(40);
push(50);
pop();
pop();
printf("Top now: %d\n", stack[top]);
return 0;
}
Output:
Underflow: stack empty Pushed 10 (top=0) Pushed 20 (top=1) Pushed 30 (top=2) Pushed 40 (top=3) Overflow: 50 dropped Popped 40 (top=2) Popped 30 (top=1) Top now: 20
Trace the output line by line. The very first pop() sees top == -1 and triggers underflow safely. After four pushes (10, 20, 30, 40), top is 3 (MAX - 1), so pushing 50 triggers overflow and leaves top untouched. Two pops remove 40 then 30 (LIFO!), leaving 20 at the top.
Worked example 2: Using a stack to reverse a string
Why does a stack reverse any sequence automatically? Push each character of "CAPE" from left to right, then pop until empty: last in (’E’) comes out first!
#include <stdio.h>
#include <string.h>
#define MAX 20
int main(void)
{
char word[] = "CAPE";
char st[MAX];
int top = -1;
int i, len = strlen(word);
for (i = 0; i < len; i++) {
if (top < MAX - 1) {
top++;
st[top] = word[i];
}
}
printf("Original: %s\n", word);
printf("Reversed: ");
while (top >= 0) {
printf("%c", st[top]);
top--;
}
printf("\n");
return 0;
}
Output:
Original: CAPE Reversed: EPAC
This exact trick solves a classic assignment (linked in Go further): testing whether a word is a palindrome (reads the same forwards and backwards, like "RADAR"). Push every letter of the word onto a stack, then walk through the original word from index 0 while popping one letter at a time. If every popped letter matches the original letter, the word is a palindrome!
Part 5: Where computers use stacks
Stacks are hidden inside almost every program you use:
- Function calls (the call stack): remember Unit 1 Module 3 Lesson 09? When
maincallsaverage, the computer pushes a frame holdingmain’s return address and local variables onto the call stack. Whenaveragefinishes, its frame is popped and execution resumes right wheremainleft off. If functions call too deeply without returning (for example, endless recursion), the program runs out of call stack space — literally a stack overflow. - Undo and Redo: every edit in a word processor or drawing app is pushed onto an Undo stack. Pressing Undo pops the last edit and reverses it (often pushing it onto a separate Redo stack).
- Browser Back button: each page you visit is pushed onto a history stack; clicking Back pops the current page to reveal the previous one.
- Bracket matching and expression evaluation: compilers check whether
(,{and[match by pushing opening brackets onto a stack and popping when a closing bracket arrives.
Try it 3Stack trace and rules drill
Pick a mode. "Trace" gives a sequence of Push and Pop calls and asks for the result. "Rules" tests stack concepts, preconditions and conventions.
Summary
| Idea | Remember |
| Rule | LIFO: Last-In, First-Out; all changes happen at one end (top). |
| Empty / Full (0-based) | Empty when top == -1; Full when top == MAX - 1. |
| Push(x) | Check !isFull(); increment top, then store stack[top] = x. |
| Pop() | Check !isEmpty(); read stack[top], then decrement top. |
| Peek() | Read stack[top] without removing it or changing top. |
| Errors guarded | Overflow (pushing when full) and underflow (popping when empty). |
Review questions
1. Why is a stack described as a LIFO data structure?
Show answer
LIFO stands for Last-In, First-Out: the item pushed onto the top of the stack most recently is always the first item removed by Pop.
2. List the FOUR basic stack operations in the syllabus and state what each does.
Show answer
Push (adds an item to the top), Pop (removes and returns the top item), Empty (checks whether the stack contains no items) and Full (checks whether the stack has reached maximum capacity).
3. Distinguish between stack overflow and stack underflow.
Show answer
Stack overflow happens when Push is attempted on a full stack. Stack underflow happens when Pop (or Peek) is attempted on an empty stack.
4. In a 0-based array stack of capacity 8, what value does top hold when: (a) the stack is empty, (b) it holds 3 items, (c) it is full?
Show answer
(a) -1, (b) 2 (items at indexes 0, 1, 2), (c) 7 (MAX - 1).
5. Trace the contents of a stack (start empty, top = -1) after: Push(5), Push(12), Pop(), Push(9), Push(14), Pop(). State top and the active items.
Show answer
After Push(5): [5], top=0. Push(12): [5,12], top=1. Pop(): removes 12, [5], top=0. Push(9): [5,9], top=1. Push(14): [5,9,14], top=2. Pop(): removes 14, active stack is [5, 9], top = 1.
6. Why does Pop not need to erase the removed element from the array?
Show answer
Because top moves down by 1, any value above top is outside the active stack and will be overwritten by the next Push.
7. Write pseudocode for the Push operation on a 0-based stack of size MAX.
Show answer
PROCEDURE push(item)
IF top = MAX - 1 THEN
OUTPUT "Stack Overflow"
ELSE
top ← top + 1
stack[top] ← item
ENDIF
END PROCEDURE
8. Give TWO real-world or computing applications where a stack is the right ADT, and explain why.
Show answer
Any two: browser Back history (most recently visited page is returned to first), Undo in an editor (most recent action is undone first), function call stack (most recently called function returns first), reversing a string or checking balanced brackets.
Homework
- Draw a step-by-step stack diagram (capacity 4, 0-based) for: Push(E), Push(H), Pop(), Push(J), Push(T), Pop(), Push(M). Show top at each step.
- Write pseudocode for a function peek() that returns the top item without changing top, and reports an error if the stack is empty.
- Write a C program based on reverse_word.c that reads a one-word string and prints "Palindrome" or "Not a palindrome" using a char stack.
- Describe what goes wrong if Push stores stack[top] = item BEFORE incrementing top (starting from top = -1).
- Look up how the 1-based convention (top = 0 when empty) changes the pseudocode for isEmpty, isFull, push and pop, and write out the four 1-based algorithms.
Mastery quiz: Stacks
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Stacks: LIFO, Push, Pop, Empty and Full (Diagrams and Algorithms)
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
Specimen Unit 2 Paper 01 (2021), Items 3, 7 and 14. Item 3 tests identifying LIFO as a stack. Item 7 tests pairing stack operations (Push and Pop, not Enqueue/Dequeue). Item 14 gives a sequence of Push and Pop calls and asks for the final stack diagram — always draw the array step by step and mark where top points.
Specimen Unit 2 Paper 02 (2021), Question 1(a). Explaining the structure and operations of a stack ADT. Mention the underlying storage (such as a 1-D array), the top tracker, LIFO order, and the Push/Pop operations with Full/Empty checks.
CAPE 2022 Unit 2 Paper 02, Question 1. Distinguishing a stack from a queue and describing their operations. Be crystal clear that a stack inserts and removes at the same end (top), whereas a queue inserts at the rear and removes at the front.
More worked answers are on the CS Solutions page.
Previous: Unit 2 • Module 1 • Lesson 01 – Abstract Data Types: Primitive vs Non-Primitive, Linear vs Non-Linear, and Core Operations. Next: Unit 2 • Module 1 • Lesson 03 – Building a Stack in C with an Array.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 2: distinguish among ADTs (stacks as LIFO: definition, structure and operation). Specific Objective 3: perform basic operations on standard ADTs using diagrams and algorithms (Stacks: Push, Pop, Empty, Full).
Video search terms
Search YouTube for: "stack data structure push pop", "LIFO stack animation", "stack overflow underflow explained".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/11/24
- First version of the lesson.
© 2026 islandclass.org
