Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 1 · syllabusAsked 2× in KTU papersChecked by code · teacher review pending

Stack ADT and array implementation

A last-in, first-out list where every insertion and deletion happens at one end, the top.

Syllabus says: “Stacks and Queues - Stacks”

On this page · 19 sections
ormakkurippu ✎
Never-forget card

LIFO — Last In, First Out. Empty: top = −1. Full: top = MAX − 1. PUSH = ++top, POP = top−−.

Picture it

A stack of steel plates at a sadya: the last plate washed goes on top and is the first one picked up.

Write this in the exam

A stack is an ordered list in which insertions (push) and deletions (pop) are made at one end called the top; it follows Last-In-First-Out order.

അവസാനം വന്നവൻ ആദ്യം പോകും!

Learning objectives

  • Define the stack ADT and its LIFO behaviour.
  • Write push, pop and peek for an array-based stack, with overflow and underflow checks (asked in KTU Nov 2025 Q2 and the model paper Q10a).
  • Trace a sequence of stack operations and state the final top.

Prerequisites

One-dimensional arrays and indexing from 0; functions in C; global variables.

Introduction

Think of a pile of plates in a canteen: you put a clean plate on top, and the next person takes the top plate. The plate placed last is removed first. A stack organises data the same way, and that one restriction makes it the natural tool for undo, function calls and expression evaluation.

Definition

Definition

A stack is an ordered list in which insertions (push) and deletions (pop) are made at one end only, called the top. The element inserted last is the first one removed — Last In, First Out (LIFO).

OperationMeaningError condition
push(x)insert x on topoverflow — stack is full
pop()remove and return the top elementunderflow — stack is empty
peek() / top()return the top element without removing itstack is empty
isEmpty(), isFull()test the state—

Array implementation

Use an array stack[0 … MAX−1] and an integer top that holds the index of the top element. top = −1 means the stack is empty, and top = MAX−1 means it is full.

  1. Push(x): if top = MAX−1 report overflow; otherwise top ← top + 1 and stack[top] ← x.
  2. Pop(): if top = −1 report underflow; otherwise item ← stack[top], top ← top − 1, return item.
  3. Peek(): if top = −1 the stack is empty; otherwise return stack[top].
Pro tip

Order matters: push increments top before storing; pop reads before decrementing. In C these become stack[++top] = x and return stack[top--].

Popping does not erase anything from memory. The old value stays in the array, but it is no longer part of the stack because it lies above top. The next push simply overwrites it.

Where stacks are used

  • Function calls: each call's local variables and return address live in a stack frame (the call stack).
  • Undo/redo in editors and the browser Back button.
  • Checking balanced brackets in source code.
  • Converting and evaluating expressions (next lessons).
  • Backtracking: maze solving, depth-first search.

Worked example

Worked example: MAX = 4checked by code
OperationResulttopArray (index 0 … 3)Bottom → top
push(10)ok0[10 _ _ _]10
push(20)ok1[10 20 _ _]10 20
push(30)ok2[10 20 30 _]10 20 30
popremoved 301[10 20 _ _]10 20
push(40)ok2[10 20 40 _]10 20 40
push(50)ok3[10 20 40 50]10 20 40 50
push(60)OVERFLOW3[10 20 40 50]10 20 40 50
popremoved 502[10 20 40 _]10 20 40
popremoved 401[10 20 _ _]10 20

MAX = 4. “_” marks a slot that holds no live element.

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Algorithm / pseudocode

Stack (array)
  1. 1top ← −1
  2. 2Push(x):
  3. 3if top = MAX − 1 then
  4. 4print "Stack overflow"; return
  5. 5top ← top + 1
  6. 6stack[top] ← x
  7. 7Pop():
  8. 8if top = −1 then
  9. 9print "Stack underflow"; return
  10. 10item ← stack[top]
  11. 11top ← top − 1; return item
  12. 12Peek():
  13. 13if top = −1 then
  14. 14print "Stack empty"; return
  15. 15return stack[top]
  16. 16end

C implementation

stack_array.ctested ✓ 200/200 cases
C
/* Stack using an array — KTU PCCST303, Module 1
 * top = -1 means empty. Overflow when top == MAX-1, underflow when top == -1.
 * Input : MAX (1..100), then commands until EOF:  PUSH x | POP | PEEK
 * Output: one line per command, then the final state.                  */
#include <stdio.h>
#include <string.h>

#define CAP 100
int stack[CAP];
int top = -1;
int MAX;

void push(int x) {
    if (top == MAX - 1) { printf("OVERFLOW\n"); return; }
    top = top + 1;
    stack[top] = x;
    printf("PUSHED %d\n", x);
}

void pop(void) {
    if (top == -1) { printf("UNDERFLOW\n"); return; }
    int item = stack[top];
    top = top - 1;
    printf("POPPED %d\n", item);
}

void peek(void) {
    if (top == -1) { printf("UNDERFLOW\n"); return; }
    printf("PEEK %d\n", stack[top]);
}

int main(void) {
    char cmd[16];
    int x;
    if (scanf("%d", &MAX) != 1 || MAX < 1 || MAX > CAP) return 1;
    while (scanf("%15s", cmd) == 1) {
        if (strcmp(cmd, "PUSH") == 0) { if (scanf("%d", &x) != 1) return 1; push(x); }
        else if (strcmp(cmd, "POP") == 0) pop();
        else if (strcmp(cmd, "PEEK") == 0) peek();
        else return 1;
    }
    printf("STATE top=%d\nCONTENTS:", top);              /* bottom -> top */
    for (int i = 0; i <= top; i++) printf(" %d", stack[i]);
    printf("\n");
    return 0;
}
Sample run · MAX = 3 · real output from gcc

Input (stdin)

3
PUSH 10
PUSH 20
PUSH 30
PUSH 40
POP
PEEK

Output (stdout)

PUSHED 10
PUSHED 20
PUSHED 30
OVERFLOW
POPPED 30
PEEK 20
STATE top=1
CONTENTS: 10 20

Open in the Code Lab →

Complexity

Space: O(MAX) for the array, allocated whether or not it is used.
OperationTimeReason
pushO(1)one comparison, one increment, one store
popO(1)one comparison, one read, one decrement
peekO(1)one read

Array vs linked implementation

Array stackLinked stack (Module 2)
Fixed size — overflow possibleGrows until memory runs out
No pointer overhead; cache-friendlyExtra pointer per element
Very simple codeNeeds malloc/free

Edge cases

  • Pop or peek on an empty stack → underflow; the state does not change.
  • Push on a full stack → overflow; the state does not change.
  • MAX = 1: a single push fills the stack.

Common mistakes

  • Checking top = MAX instead of top = MAX − 1 for overflow (off by one).
  • Storing first and then incrementing (stack[top++] = x) with top starting at −1 — this writes to stack[−1].
  • Forgetting to return or print the popped value in the algorithm.
  • Writing ‘delete the element’ — pop only moves top; nothing is erased.

Asked in KTU exams (2)

Quick check — can you get them all?

Question 1

Q1.Push 1, 2, 3, pop, push 4, pop, pop. What remains?

Question 2

Q2.Array stack of size MAX: the overflow condition is…

Question 3

Q3.Which is NOT a typical stack application?

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • LIFO; one end (top). Empty: top = −1. Full: top = MAX − 1.
  • Push: check full → top++ → stack[top] = x.
  • Pop: check empty → item = stack[top] → top-- → return item.
  • All operations O(1).

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 3 (Stacks and Queues) §3.1
  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — §10.1 (Stacks and queues)

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)