Model Question Paper (as circulated)Part B · Q10a5 marksCO1Module 1
Question 10a
Write an algorithm for push and pop stack operation using arrays.
Topics: Stack ADT and array implementation
Watch this exact question run
Loading visualizer…
Solution
Assumptions:
- Array stack[0 … MAX−1]; top = −1 when empty (Horowitz convention).
algorithm
Algorithm Push(x)
1. if top = MAX − 1 then
2. print "Stack overflow"; return
3. top ← top + 1
4. stack[top] ← x
Algorithm Pop()
1. if top = −1 then
2. print "Stack underflow"; return
3. item ← stack[top]
4. top ← top − 1
5. return item| Operation | Result | top | Array (index 0 … 2) | Bottom → top |
|---|---|---|---|---|
| pop | UNDERFLOW | -1 | [_ _ _] | empty |
| push(10) | ok | 0 | [10 _ _] | 10 |
| push(20) | ok | 1 | [10 20 _] | 10 20 |
| push(30) | ok | 2 | [10 20 30] | 10 20 30 |
| push(40) | OVERFLOW | 2 | [10 20 30] | 10 20 30 |
| pop | removed 30 | 1 | [10 20 _] | 10 20 |
| pop | removed 20 | 0 | [10 _ _] | 10 |
MAX = 3. “_” marks a slot that holds no live element.
How to write it in the exam
- Initially top = −1.
- Push: if top = MAX − 1 → overflow; else top = top + 1, stack[top] = x.
- Pop: if top = −1 → underflow; else item = stack[top], top = top − 1, return item.
- Both are O(1).
How this answer was verified
- tests/linear-expression.test.ts — 400 random operation sequences against an independent reference model
- stack_array.c compiled with -Werror and sanitizers; matches the engine on 200 random cases