Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
B.Tech S3 (R) (FT/WP) Examination November 2025 (2024 Scheme)QP 06PCCST303112503Part A · Q23 marksCO1Module 1

Question 2

Write algorithm for push and pop operations of a stack using array.

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
Check it on an example: MAX = 3 (shows both underflow and overflow)checked by code
OperationResulttopArray (index 0 … 2)Bottom → top
popUNDERFLOW-1[_ _ _]empty
push(10)ok0[10 _ _]10
push(20)ok1[10 20 _]10 20
push(30)ok2[10 20 30]10 20 30
push(40)OVERFLOW2[10 20 30]10 20 30
popremoved 301[10 20 _]10 20
popremoved 200[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

Similar questions