C Code Lab
31 exam-style C programs, one for every algorithm in the visualizers. Each one is compiled and tested automatically (details below). Copy any program into your own compiler (gcc, Code::Blocks, Turbo C++ in C mode, or an online compiler); every program reads from stdin, so you can paste the sample input below it.
struct node. Rather than ship something that runs only toy code, every program here shows a real sample run captured from gcc. No code is ever executed on our server.How these programs are verified
- Compiled with
gcc (Debian 14.2.0-19) 14.2.0using-std=c11 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined -fno-sanitize-recover=all -O1. Any warning fails the build; any memory error, leak or undefined behaviour aborts the run. - Lab-record programs (written like the KTU lab manual: prompts, then the result) are checked character for character against the exact text they must print, on KTU exam inputs, edge cases, duplicates, full 100-element arrays and seeded random inputs. Where a visualizer exists, their results are cross-checked with its engine too.
- Trace programs print their state after every pass, probe or operation. That output is compared line by line with the TypeScript engine behind the visualizer.
- All 31 programs pass: 7,284 test cases. Last run: Thu, 26 Nov 2026 15:47:13 GMT.
Module 1
stack_array.ctested ✓ 200/200Checked against: TS engine "stack" — outcome of every operation, final pointers and contents · Lesson: Stack ADT and array implementation
Open the lesson: Stack ADT and array implementation →
/* 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
circular_queue.ctested ✓ 200/200Checked against: TS engine "circular" — outcome of every operation, final pointers and contents · Lesson: Circular queues
Open the lesson: Circular queues →
/* Circular queue using an array — KTU PCCST303, Module 1
* front = rear = -1 means empty; all MAX slots are usable.
* Full when (rear + 1) % MAX == front.
* Input : MAX (1..100), then commands until EOF: INSERT x | DELETE */
#include <stdio.h>
#include <string.h>
#define CAP 100
int q[CAP];
int front = -1, rear = -1;
int MAX;
void insert(int x) {
if ((rear + 1) % MAX == front) { printf("OVERFLOW\n"); return; }
if (front == -1) { front = 0; rear = 0; }
else rear = (rear + 1) % MAX;
q[rear] = x;
printf("INSERTED %d\n", x);
}
void delete(void) {
if (front == -1) { printf("UNDERFLOW\n"); return; }
int item = q[front];
if (front == rear) { front = -1; rear = -1; }
else front = (front + 1) % MAX;
printf("DELETED %d\n", item);
}
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, "INSERT") == 0) { if (scanf("%d", &x) != 1) return 1; insert(x); }
else if (strcmp(cmd, "DELETE") == 0) delete();
else return 1;
}
printf("STATE front=%d rear=%d\nCONTENTS:", front, rear);
if (front != -1)
for (int i = front; ; i = (i + 1) % MAX) { /* walk front -> rear */
printf(" %d", q[i]);
if (i == rear) break;
}
printf("\n");
return 0;
}
Sample run · MAX = 3 · real output from gcc
Input (stdin)
3 INSERT 10 INSERT 20 INSERT 30 DELETE INSERT 40 INSERT 50
Output (stdout)
INSERTED 10 INSERTED 20 INSERTED 30 DELETED 10 INSERTED 40 OVERFLOW STATE front=1 rear=0 CONTENTS: 20 30 40
deque_array.ctested ✓ 200/200Checked against: TS engine "deque" — outcome of every operation, final pointers and contents · Lesson: Double-ended queues
Open the lesson: Double-ended queues →
/* Double-ended queue using a circular array — KTU PCCST303, Module 1
* front = rear = -1 means empty. Full when (rear + 1) % MAX == front.
* Input : MAX (1..100), then commands until EOF:
* INSERTFRONT x | INSERTREAR x | DELETEFRONT | DELETEREAR */
#include <stdio.h>
#include <string.h>
#define CAP 100
int dq[CAP];
int front = -1, rear = -1;
int MAX;
int is_full(void) { return (rear + 1) % MAX == front; }
int is_empty(void) { return front == -1; }
void insert_front(int x) {
if (is_full()) { printf("OVERFLOW\n"); return; }
if (is_empty()) { front = 0; rear = 0; }
else front = (front - 1 + MAX) % MAX; /* step back, wrapping */
dq[front] = x;
printf("INSERTED %d\n", x);
}
void insert_rear(int x) {
if (is_full()) { printf("OVERFLOW\n"); return; }
if (is_empty()) { front = 0; rear = 0; }
else rear = (rear + 1) % MAX;
dq[rear] = x;
printf("INSERTED %d\n", x);
}
void delete_front(void) {
if (is_empty()) { printf("UNDERFLOW\n"); return; }
int item = dq[front];
if (front == rear) { front = -1; rear = -1; }
else front = (front + 1) % MAX;
printf("DELETED %d\n", item);
}
void delete_rear(void) {
if (is_empty()) { printf("UNDERFLOW\n"); return; }
int item = dq[rear];
if (front == rear) { front = -1; rear = -1; }
else rear = (rear - 1 + MAX) % MAX;
printf("DELETED %d\n", item);
}
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, "INSERTFRONT") == 0) { if (scanf("%d", &x) != 1) return 1; insert_front(x); }
else if (strcmp(cmd, "INSERTREAR") == 0) { if (scanf("%d", &x) != 1) return 1; insert_rear(x); }
else if (strcmp(cmd, "DELETEFRONT") == 0) delete_front();
else if (strcmp(cmd, "DELETEREAR") == 0) delete_rear();
else return 1;
}
printf("STATE front=%d rear=%d\nCONTENTS:", front, rear);
if (front != -1)
for (int i = front; ; i = (i + 1) % MAX) {
printf(" %d", dq[i]);
if (i == rear) break;
}
printf("\n");
return 0;
}
Sample run · MAX = 4 · real output from gcc
Input (stdin)
4 INSERTREAR 10 INSERTFRONT 5 INSERTREAR 20 DELETEFRONT DELETEREAR
Output (stdout)
INSERTED 10 INSERTED 5 INSERTED 20 DELETED 5 DELETED 20 STATE front=0 rear=0 CONTENTS: 10
infix_to_postfix.ctested ✓ 408/408Checked against: TS runExpression (convert) — postfix output, and errors on malformed input · Lesson: Infix to postfix conversion
Open the lesson: Infix to postfix conversion →
/* Infix to postfix conversion using a stack — KTU PCCST303, Module 1
* Operands: single letters or whole numbers. Operators: + - * / % ^
* Precedence: ^ (right-associative) > * / % > + - (others left-assoc.)
* Input : one infix expression per line.
* Output: "POSTFIX: tokens separated by spaces" or "ERROR: reason" */
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define MAXTOK 64
char tok[MAXTOK][12]; /* tokens of the input */
int ntok;
char stack[MAXTOK][12]; /* operator stack */
int top = -1;
int prec(const char *t) {
switch (t[0]) {
case '^': return 3;
case '*': case '/': case '%': return 2;
case '+': case '-': return 1;
default: return 0; /* '(' or not an operator */
}
}
int is_operator(const char *t) { return t[1] == '\0' && strchr("+-*/%^", t[0]) != NULL; }
int is_operand(const char *t) { return isalnum((unsigned char)t[0]); }
/* Split the line into tokens; returns 0 on an illegal character. */
int tokenize(const char *s) {
ntok = 0;
for (int i = 0; s[i] != '\0' && s[i] != '\n'; ) {
unsigned char c = (unsigned char)s[i];
if (isspace(c)) { i++; continue; }
if (ntok == MAXTOK) return 0;
if (isdigit(c)) { /* whole number */
int j = 0;
while (isdigit((unsigned char)s[i])) {
if (j == 9) return 0; /* at most 9 digits */
tok[ntok][j++] = s[i++];
}
tok[ntok][j] = '\0';
/* drop leading zeros so "007" prints as "7" */
char *p = tok[ntok];
while (p[0] == '0' && p[1] != '\0') p++;
memmove(tok[ntok], p, strlen(p) + 1);
} else if (isalpha(c) || strchr("+-*/%^()", c) != NULL) {
tok[ntok][0] = (char)c; tok[ntok][1] = '\0'; i++;
} else return 0;
ntok++;
}
return ntok > 0;
}
/* Operand/operator must alternate and parentheses must balance. */
int valid(void) {
int expect_operand = 1, depth = 0;
for (int k = 0; k < ntok; k++) {
const char *t = tok[k];
if (expect_operand) {
if (is_operand(t)) expect_operand = 0;
else if (t[0] == '(') depth++;
else return 0;
} else {
if (is_operator(t)) expect_operand = 1;
else if (t[0] == ')') { if (--depth < 0) return 0; }
else return 0;
}
}
return !expect_operand && depth == 0;
}
void push(const char *t) { strcpy(stack[++top], t); }
const char *pop(void) { return stack[top--]; }
int main(void) {
char line[512];
while (fgets(line, sizeof line, stdin) != NULL) {
if (!tokenize(line) || !valid()) { printf("ERROR: invalid expression\n"); continue; }
top = -1;
printf("POSTFIX:");
for (int k = 0; k < ntok; k++) {
const char *t = tok[k];
if (is_operand(t)) printf(" %s", t);
else if (t[0] == '(') push(t);
else if (t[0] == ')') {
while (stack[top][0] != '(') printf(" %s", pop());
top--; /* discard '(' */
} else {
while (top >= 0 && stack[top][0] != '(' &&
(prec(stack[top]) > prec(t) ||
(prec(stack[top]) == prec(t) && t[0] != '^')))
printf(" %s", pop());
push(t);
}
}
while (top >= 0) printf(" %s", pop());
printf("\n");
}
return 0;
}
Sample run · Nov 2025 Q10a and May 2026 Q10a · real output from gcc
Input (stdin)
(A+B*C/D)-(E-F/G) A+(B-C/D*E)+F/G
Output (stdout)
POSTFIX: A B C * D / + E F G / - - POSTFIX: A B C D / E * - + F G / +
postfix_eval.ctested ✓ 400/400Checked against: TS runExpression (evaluate, integer mode) — result or error · Lesson: Evaluating postfix expressions
Open the lesson: Evaluating postfix expressions →
/* Evaluation of a postfix expression using a stack — KTU PCCST303, Module 1
* Tokens are whole numbers and the operators + - * / % ^, separated by spaces.
* Integer arithmetic as in C: / truncates toward zero, % takes the sign of the
* dividend. Values are limited to +/- 10^15 to rule out overflow.
* Input : one postfix expression per line.
* Output: "RESULT: value" or "ERROR: reason" */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LIMIT 1000000000000000LL /* 10^15 */
#define MAXSTACK 64
long long stack[MAXSTACK];
int top = -1;
/* Returns 1 and stores the result in *r, or returns 0 with *err set. */
int apply(long long a, char op, long long b, long long *r, const char **err) {
switch (op) {
case '+': *r = a + b; break;
case '-': *r = a - b; break;
case '*':
if (a != 0 && llabs(b) > LIMIT / llabs(a)) { *err = "value too large"; return 0; }
*r = a * b; break;
case '/': if (b == 0) { *err = "division by zero"; return 0; } *r = a / b; break;
case '%': if (b == 0) { *err = "division by zero"; return 0; } *r = a % b; break;
case '^':
if (b < 0) { *err = "negative exponent"; return 0; }
if (a == 0 || a == 1) { *r = (b == 0) ? 1 : a; break; }
if (a == -1) { *r = (b % 2 == 0) ? 1 : -1; break; }
*r = 1;
for (long long i = 0; i < b; i++) {
if (llabs(*r) > LIMIT / llabs(a)) { *err = "value too large"; return 0; }
*r *= a;
}
break;
default: *err = "unknown operator"; return 0;
}
if (*r > LIMIT || *r < -LIMIT) { *err = "value too large"; return 0; }
return 1;
}
const char *evaluate(char *line, long long *result) {
top = -1;
for (char *t = strtok(line, " \t\r\n"); t != NULL; t = strtok(NULL, " \t\r\n")) {
if (isdigit((unsigned char)t[0])) {
if (top == MAXSTACK - 1) return "stack overflow";
stack[++top] = strtoll(t, NULL, 10);
} else if (t[1] == '\0' && strchr("+-*/%^", t[0]) != NULL) {
if (top < 1) return "operator needs two operands";
long long b = stack[top--]; /* right operand first! */
long long a = stack[top--];
long long r;
const char *err = NULL;
if (!apply(a, t[0], b, &r, &err)) return err;
stack[++top] = r;
} else return "bad token";
}
if (top != 0) return "invalid postfix expression";
*result = stack[0];
return NULL;
}
int main(void) {
char line[512];
while (fgets(line, sizeof line, stdin) != NULL) {
long long r = 0;
const char *err = evaluate(line, &r);
if (err) printf("ERROR: %s\n", err);
else printf("RESULT: %lld\n", r);
}
return 0;
}
Sample run · model Q11a · real output from gcc
Input (stdin)
4 5 * 3 / 4 2 % - 1 5 * + 2 -
Output (stdout)
RESULT: 9
linear_queue.ctested ✓ 220/220Checked against: exact output text of the menu program (reference model of the Step algorithm); every insert/delete outcome and the final contents also match the TS queue engine · Lesson: Queue ADT (linear queue)
Open the lesson: Queue ADT (linear queue) →
/* Queue using Array — KTU PCCST303, Module 1 (lab-record style)
* front = rear = -1 means the queue is empty. */
#include <stdio.h>
#define MAX 5
int queue[MAX], front = -1, rear = -1;
void enqueue()
{
int item;
if (rear == MAX - 1) {
printf("Queue Overflow\n");
return;
}
printf("Enter the element to insert: ");
scanf("%d", &item);
if (front == -1)
front = 0;
rear++;
queue[rear] = item;
printf("Element inserted successfully\n");
}
void dequeue()
{
if (front == -1 || front > rear) {
printf("Queue Underflow\n");
return;
}
printf("Deleted element: %d\n", queue[front]);
front++;
if (front > rear) /* queue became empty */
front = rear = -1;
}
void display()
{
int i;
if (front == -1) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
for (i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}
int main()
{
int choice;
while (1) {
printf("\n1. Insert 2. Delete 3. Display 4. Exit\n");
printf("Enter your choice: ");
if (scanf("%d", &choice) != 1) /* end of input */
break;
if (choice == 1)
enqueue();
else if (choice == 2)
dequeue();
else if (choice == 3)
display();
else if (choice == 4)
break;
else
printf("Invalid choice\n");
}
return 0;
}
Sample input / output · MAX = 5 · real run, compiled with gcc
1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 1 Enter the element to insert: 10 Element inserted successfully 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 1 Enter the element to insert: 20 Element inserted successfully 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 1 Enter the element to insert: 30 Element inserted successfully 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 3 Queue elements: 10 20 30 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 2 Deleted element: 10 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 3 Queue elements: 20 30 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 5 Invalid choice 1. Insert 2. Delete 3. Display 4. Exit Enter your choice: 4
Bold = what you type. Everything else is printed by the program.
polynomial_add_array.ctested ✓ 220/220Checked against: exact output text; every term of the sum comes from TS runPolyAdd (cancelled terms dropped) · Lesson: Polynomial representation using arrays
Open the lesson: Polynomial representation using arrays →
/* Polynomial Addition using Arrays of terms — KTU PCCST303, Module 1 (lab-record style)
* Enter each term as: coefficient exponent, in descending order of exponent. */
#include <stdio.h>
struct Term {
int coeff, exp;
};
int main()
{
struct Term p1[20], p2[20], sum[40];
int n1, n2, i, j, k;
printf("Enter number of terms in first polynomial: ");
scanf("%d", &n1);
printf("Enter coefficient and exponent of each term (descending order of exponent):\n");
for (i = 0; i < n1; i++)
scanf("%d %d", &p1[i].coeff, &p1[i].exp);
printf("Enter number of terms in second polynomial: ");
scanf("%d", &n2);
printf("Enter coefficient and exponent of each term (descending order of exponent):\n");
for (i = 0; i < n2; i++)
scanf("%d %d", &p2[i].coeff, &p2[i].exp);
i = 0;
j = 0;
k = 0;
while (i < n1 && j < n2) {
if (p1[i].exp > p2[j].exp) {
sum[k] = p1[i];
i++;
k++;
}
else if (p1[i].exp < p2[j].exp) {
sum[k] = p2[j];
j++;
k++;
}
else { /* equal exponents: add */
if (p1[i].coeff + p2[j].coeff != 0) {
sum[k].coeff = p1[i].coeff + p2[j].coeff;
sum[k].exp = p1[i].exp;
k++;
}
i++;
j++;
}
}
while (i < n1) { /* remaining terms of p1 */
sum[k] = p1[i];
i++;
k++;
}
while (j < n2) { /* remaining terms of p2 */
sum[k] = p2[j];
j++;
k++;
}
printf("Sum = ");
if (k == 0)
printf("0");
for (i = 0; i < k; i++) {
if (i == 0)
printf("%dx^%d", sum[i].coeff, sum[i].exp);
else if (sum[i].coeff < 0)
printf(" - %dx^%d", -sum[i].coeff, sum[i].exp);
else
printf(" + %dx^%d", sum[i].coeff, sum[i].exp);
}
printf("\n");
return 0;
}
Sample input / output · model Q12a · real run, compiled with gcc
Enter number of terms in first polynomial: 4 Enter coefficient and exponent of each term (descending order of exponent): 2 3 5 2 -4 1 5 0 Enter number of terms in second polynomial: 4 Enter coefficient and exponent of each term (descending order of exponent): 4 3 2 2 3 1 -6 0 Sum = 6x^3 + 7x^2 - 1x^1 - 1x^0
Bold = what you type. Everything else is printed by the program.
sparse_transpose.ctested ✓ 240/240Checked against: TS runTranspose (simple and fast) — every output triple in order · Lesson: Sparse matrix — tuple representation
Open the lesson: Sparse matrix — tuple representation →
/* Sparse matrix: triple representation, simple and fast transpose — KTU PCCST303, Module 1
* a[0] = (rows, cols, t); a[1..t] = (row, col, value) in row-major order.
* Input : S|F rows cols then the matrix row by row.
* Output: "B: r c v" for b[0..t] (b[0] is the header of the transpose). */
#include <stdio.h>
#define MAXT 101
struct triple { int row, col, value; };
void simpleTranspose(struct triple a[], struct triple b[]) {
int n = a[0].value, k = 1, c, i;
b[0].row = a[0].col; b[0].col = a[0].row; b[0].value = n;
for (c = 0; c < a[0].col; c++) /* for every column of A ... */
for (i = 1; i <= n; i++) /* ... scan all t triples: O(cols·t) */
if (a[i].col == c) {
b[k].row = a[i].col; b[k].col = a[i].row; b[k].value = a[i].value;
k++;
}
}
void fastTranspose(struct triple a[], struct triple b[]) {
int rowTerms[MAXT] = {0}, startPos[MAXT];
int n = a[0].value, cols = a[0].col, i, j;
b[0].row = cols; b[0].col = a[0].row; b[0].value = n;
if (n == 0) return;
for (i = 1; i <= n; i++) rowTerms[a[i].col]++; /* terms per column */
startPos[0] = 1;
for (i = 1; i < cols; i++) startPos[i] = startPos[i - 1] + rowTerms[i - 1];
for (i = 1; i <= n; i++) { /* place each triple directly */
j = startPos[a[i].col]++;
b[j].row = a[i].col; b[j].col = a[i].row; b[j].value = a[i].value;
}
}
int main(void) {
struct triple a[MAXT], b[MAXT];
char algo[4];
int rows, cols, r, c, x, t = 0, i;
if (scanf("%3s %d %d", algo, &rows, &cols) != 3 || rows < 1 || cols < 1 || rows * cols > MAXT - 1) { printf("BAD INPUT\n"); return 1; }
for (r = 0; r < rows; r++)
for (c = 0; c < cols; c++) {
if (scanf("%d", &x) != 1) { printf("BAD INPUT\n"); return 1; }
if (x != 0) { t++; a[t].row = r; a[t].col = c; a[t].value = x; }
}
a[0].row = rows; a[0].col = cols; a[0].value = t;
if (algo[0] == 'F') fastTranspose(a, b); else simpleTranspose(a, b);
for (i = 0; i <= t; i++) printf("B: %d %d %d\n", b[i].row, b[i].col, b[i].value);
return 0;
}
Sample run · fast transpose · real output from gcc
Input (stdin)
F 4 5 0 0 3 0 4 0 0 5 7 0 0 0 0 0 0 0 2 6 0 0
Output (stdout)
B: 5 4 6 B: 1 3 2 B: 2 0 3 B: 2 1 5 B: 2 3 6 B: 3 1 7 B: 4 0 4
Module 2
singly_linked_list.ctested ✓ 160/160Checked against: TS runList (singly) — result line and full list after every operation; ASan leak check · Lesson: Singly linked lists and their operations
Open the lesson: Singly linked lists and their operations →
/* Singly linked list — KTU PCCST303, Module 2
* struct node is self-referential: each node stores data and a pointer to the next node.
* Commands (one per line, until EOF):
* IF x insert at front IE x insert at end IA k x insert x after key k
* D x delete first x S x search x R reverse in place
* T traverse: count the nodes and find the largest element (KTU Nov 2025 Q4, May 2026 Q4)
* After every command: an optional result line, then "LIST: ..." (first → last). */
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
struct node *getNode(int x) {
struct node *n = malloc(sizeof *n);
if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
n->data = x;
n->next = NULL;
return n;
}
void insertFront(int x) {
struct node *n = getNode(x);
n->next = head; /* new node points to the old first node ... */
head = n; /* ... then head moves to the new node */
}
void insertEnd(int x) {
struct node *n = getNode(x), *p;
if (head == NULL) { head = n; return; }
p = head;
while (p->next != NULL) p = p->next; /* walk to the last node */
p->next = n;
}
void insertAfter(int key, int x) {
struct node *p = head, *n;
while (p != NULL && p->data != key) p = p->next;
if (p == NULL) { printf("key %d not found\n", key); return; }
n = getNode(x);
n->next = p->next; /* order matters: link the new node first */
p->next = n;
}
void deleteKey(int x) {
struct node *p, *prev;
if (head == NULL) { printf("UNDERFLOW\n"); return; }
if (head->data == x) { p = head; head = head->next; free(p); return; }
prev = head;
p = head->next;
while (p != NULL && p->data != x) { prev = p; p = p->next; }
if (p == NULL) { printf("%d not found\n", x); return; }
prev->next = p->next; /* bypass p */
free(p);
}
void search(int x) {
struct node *p = head;
int pos = 1;
while (p != NULL) {
if (p->data == x) { printf("found at position %d\n", pos); return; }
p = p->next;
pos++;
}
printf("%d not found\n", x);
}
void reverse(void) {
struct node *prev = NULL, *p = head, *nxt;
while (p != NULL) {
nxt = p->next; /* remember the rest of the list */
p->next = prev; /* flip the link */
prev = p;
p = nxt;
}
head = prev;
}
void traverse(void) {
struct node *p = head;
int count = 0, max;
if (head == NULL) { printf("empty list\n"); return; }
max = head->data;
while (p != NULL) {
count++;
if (p->data > max) max = p->data;
p = p->next;
}
printf("count = %d, largest = %d\n", count, max);
}
void display(void) {
struct node *p;
printf("LIST:");
for (p = head; p != NULL; p = p->next) printf(" %d", p->data);
printf("\n");
}
int main(void) {
char cmd[8];
int a, b;
while (scanf("%7s", cmd) == 1) {
if (cmd[0] == 'I' && cmd[1] == 'F' && scanf("%d", &a) == 1) insertFront(a);
else if (cmd[0] == 'I' && cmd[1] == 'E' && scanf("%d", &a) == 1) insertEnd(a);
else if (cmd[0] == 'I' && cmd[1] == 'A' && scanf("%d %d", &a, &b) == 2) insertAfter(a, b);
else if (cmd[0] == 'D' && scanf("%d", &a) == 1) deleteKey(a);
else if (cmd[0] == 'S' && scanf("%d", &a) == 1) search(a);
else if (cmd[0] == 'R') reverse();
else if (cmd[0] == 'T') traverse();
else { printf("BAD COMMAND\n"); break; }
display();
}
while (head != NULL) { struct node *t = head; head = head->next; free(t); }
return 0;
}
Sample run · count and largest (Nov 2025 Q4) · real output from gcc
Input (stdin)
IE 12 IE 45 IE 7 IE 30 T D 7 R
Output (stdout)
LIST: 12 LIST: 12 45 LIST: 12 45 7 LIST: 12 45 7 30 count = 4, largest = 45 LIST: 12 45 7 30 LIST: 12 45 30 LIST: 30 45 12
doubly_linked_list.ctested ✓ 160/160Checked against: TS runList (doubly) — result line and full list after every operation, plus the list walked backwards via prev; ASan leak check · Lesson: Doubly linked lists
Open the lesson: Doubly linked lists →
/* Doubly linked list — KTU PCCST303, Module 2
* Each node has prev and next, so the list can be walked in both directions.
* Commands: IF x | IE x | IA k x | D x | S x | DR (display in reverse, KTU Nov 2025 Q12b)
* After every command: optional result line, "LIST: ..." (via next) and
* "BACK: ..." (from the last node via prev — checks every prev pointer). */
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *prev;
int data;
struct node *next;
};
struct node *head = NULL;
struct node *getNode(int x) {
struct node *n = malloc(sizeof *n);
if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
n->data = x;
n->prev = n->next = NULL;
return n;
}
void insertFront(int x) {
struct node *n = getNode(x);
n->next = head;
if (head != NULL) head->prev = n; /* old first node points back to the new one */
head = n;
}
void insertEnd(int x) {
struct node *n = getNode(x), *p;
if (head == NULL) { head = n; return; }
for (p = head; p->next != NULL; p = p->next) { }
p->next = n;
n->prev = p;
}
void insertAfter(int key, int x) {
struct node *p = head, *n;
while (p != NULL && p->data != key) p = p->next;
if (p == NULL) { printf("key %d not found\n", key); return; }
n = getNode(x);
n->prev = p; /* 4 pointer changes */
n->next = p->next;
if (p->next != NULL) p->next->prev = n;
p->next = n;
}
void deleteKey(int x) {
struct node *p = head;
if (head == NULL) { printf("UNDERFLOW\n"); return; }
while (p != NULL && p->data != x) p = p->next;
if (p == NULL) { printf("%d not found\n", x); return; }
if (p->prev != NULL) p->prev->next = p->next; else head = p->next;
if (p->next != NULL) p->next->prev = p->prev;
free(p);
}
void search(int x) {
struct node *p = head;
int pos = 1;
for (; p != NULL; p = p->next, pos++)
if (p->data == x) { printf("found at position %d\n", pos); return; }
printf("%d not found\n", x);
}
void displayReverse(void) {
struct node *p = head;
if (head == NULL) { printf("empty list\n"); return; }
while (p->next != NULL) p = p->next; /* go to the last node */
printf("reverse:");
for (; p != NULL; p = p->prev) printf(" %d", p->data);
printf("\n");
}
void display(void) {
struct node *p, *last = NULL;
printf("LIST:");
for (p = head; p != NULL; p = p->next) { printf(" %d", p->data); last = p; }
printf("\nBACK:");
for (p = last; p != NULL; p = p->prev) printf(" %d", p->data);
printf("\n");
}
int main(void) {
char cmd[8];
int a, b;
while (scanf("%7s", cmd) == 1) {
if (cmd[0] == 'I' && cmd[1] == 'F' && scanf("%d", &a) == 1) insertFront(a);
else if (cmd[0] == 'I' && cmd[1] == 'E' && scanf("%d", &a) == 1) insertEnd(a);
else if (cmd[0] == 'I' && cmd[1] == 'A' && scanf("%d %d", &a, &b) == 2) insertAfter(a, b);
else if (cmd[0] == 'D' && cmd[1] == 'R') displayReverse();
else if (cmd[0] == 'D' && scanf("%d", &a) == 1) deleteKey(a);
else if (cmd[0] == 'S' && scanf("%d", &a) == 1) search(a);
else { printf("BAD COMMAND\n"); break; }
display();
}
while (head != NULL) { struct node *t = head; head = head->next; free(t); }
return 0;
}
Sample run · display in reverse (Nov 2025 Q12b) · real output from gcc
Input (stdin)
IE 10 IE 20 IF 5 IA 10 15 D 20 DR
Output (stdout)
LIST: 10 BACK: 10 LIST: 10 20 BACK: 20 10 LIST: 5 10 20 BACK: 20 10 5 LIST: 5 10 15 20 BACK: 20 15 10 5 LIST: 5 10 15 BACK: 15 10 5 reverse: 15 10 5 LIST: 5 10 15 BACK: 15 10 5
circular_linked_list.ctested ✓ 160/160Checked against: TS runList (circular) — result line and full list after every operation; ASan leak check · Lesson: Circular linked lists
Open the lesson: Circular linked lists →
/* Circular singly linked list — KTU PCCST303, Module 2
* We keep a pointer to the LAST node: last->next is the first node, so both
* insert-at-front and insert-at-end are O(1) (KTU Nov 2025 Q11b).
* Commands: IF x | IE x | D x | S x | T (count + largest)
* After every command: optional result line, then "LIST: ..." (first → last). */
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *last = NULL;
struct node *getNode(int x) {
struct node *n = malloc(sizeof *n);
if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
n->data = x;
n->next = NULL;
return n;
}
void insertFront(int x) {
struct node *n = getNode(x);
if (last == NULL) { n->next = n; last = n; return; } /* one node points to itself */
n->next = last->next;
last->next = n;
}
void insertEnd(int x) {
insertFront(x); /* insert at the front ... */
last = last->next; /* ... and move last onto the new node: O(1) */
}
void deleteKey(int x) {
struct node *prev, *p;
if (last == NULL) { printf("UNDERFLOW\n"); return; }
prev = last;
p = last->next;
while (p->data != x && p != last) { prev = p; p = p->next; }
if (p->data != x) { printf("%d not found\n", x); return; }
if (p == prev) last = NULL; /* it was the only node */
else {
prev->next = p->next;
if (p == last) last = prev;
}
free(p);
}
void search(int x) {
struct node *p;
int pos = 1;
if (last == NULL) { printf("not found (empty)\n"); return; }
p = last->next;
do {
if (p->data == x) { printf("found at position %d\n", pos); return; }
p = p->next;
pos++;
} while (p != last->next);
printf("%d not found\n", x);
}
void traverse(void) {
struct node *p;
int count = 0, max;
if (last == NULL) { printf("empty list\n"); return; }
p = last->next;
max = p->data;
do { /* stop when we come back to the first node */
count++;
if (p->data > max) max = p->data;
p = p->next;
} while (p != last->next);
printf("count = %d, largest = %d\n", count, max);
}
void display(void) {
struct node *p;
printf("LIST:");
if (last != NULL) {
p = last->next;
do { printf(" %d", p->data); p = p->next; } while (p != last->next);
}
printf("\n");
}
int main(void) {
char cmd[8];
int a;
while (scanf("%7s", cmd) == 1) {
if (cmd[0] == 'I' && cmd[1] == 'F' && scanf("%d", &a) == 1) insertFront(a);
else if (cmd[0] == 'I' && cmd[1] == 'E' && scanf("%d", &a) == 1) insertEnd(a);
else if (cmd[0] == 'D' && scanf("%d", &a) == 1) deleteKey(a);
else if (cmd[0] == 'S' && scanf("%d", &a) == 1) search(a);
else if (cmd[0] == 'T') traverse();
else { printf("BAD COMMAND\n"); break; }
display();
}
while (last != NULL) {
struct node *first = last->next;
if (first == last) { free(first); last = NULL; }
else { last->next = first->next; free(first); }
}
return 0;
}
Sample run · insert at front and end (Nov 2025 Q11b) · real output from gcc
Input (stdin)
IE 10 IE 20 IF 5 IE 30 T D 30
Output (stdout)
LIST: 10 LIST: 10 20 LIST: 5 10 20 LIST: 5 10 20 30 count = 4, largest = 30 LIST: 5 10 20 30 LIST: 5 10 20
linked_stack_queue.ctested ✓ 320/320Checked against: TS runList (stack, queue) — result line and full list after every operation; ASan leak check · Lesson: Stacks and queues using linked lists
Open the lesson: Stacks and queues using linked lists →
/* Stack and queue using linked lists — KTU PCCST303, Module 2
* Linked stack: push and pop at the front (top). Linked queue: insert at rear, delete at front.
* No overflow check is needed except when malloc fails.
* First line: S (stack) or Q (queue). Then commands: PUSH x | POP | PEEK or ENQ x | DEQ
* After every command: optional result line, then "LIST: ..." (top→bottom or front→rear). */
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *top = NULL; /* stack */
struct node *front = NULL, *rear = NULL; /* queue */
struct node *getNode(int x) {
struct node *n = malloc(sizeof *n);
if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
n->data = x;
n->next = NULL;
return n;
}
void push(int x) { struct node *n = getNode(x); n->next = top; top = n; }
void pop(void) {
struct node *t;
if (top == NULL) { printf("UNDERFLOW\n"); return; }
t = top;
top = top->next;
printf("popped %d\n", t->data);
free(t);
}
void peek(void) {
if (top == NULL) { printf("UNDERFLOW\n"); return; }
printf("top is %d\n", top->data);
}
void enqueue(int x) {
struct node *n = getNode(x);
if (rear == NULL) front = rear = n; /* first node is both front and rear */
else { rear->next = n; rear = n; }
}
void dequeue(void) {
struct node *t;
if (front == NULL) { printf("UNDERFLOW\n"); return; }
t = front;
front = front->next;
if (front == NULL) rear = NULL; /* queue became empty */
printf("dequeued %d\n", t->data);
free(t);
}
void display(struct node *p) {
printf("LIST:");
for (; p != NULL; p = p->next) printf(" %d", p->data);
printf("\n");
}
int main(void) {
char kind[4], cmd[8];
int x;
if (scanf("%3s", kind) != 1) return 1;
while (scanf("%7s", cmd) == 1) {
if (cmd[0] == 'P' && cmd[1] == 'U' && scanf("%d", &x) == 1) push(x);
else if (cmd[0] == 'P' && cmd[1] == 'O') pop();
else if (cmd[0] == 'P' && cmd[1] == 'E') peek();
else if (cmd[0] == 'E' && scanf("%d", &x) == 1) enqueue(x);
else if (cmd[0] == 'D') dequeue();
else { printf("BAD COMMAND\n"); break; }
display(kind[0] == 'S' ? top : front);
}
while (top != NULL) { struct node *t = top; top = top->next; free(t); }
while (front != NULL) { struct node *t = front; front = front->next; free(t); }
return 0;
}
Sample run · linked queue · real output from gcc
Input (stdin)
Q ENQ 10 ENQ 20 DEQ ENQ 30 DEQ DEQ DEQ
Output (stdout)
LIST: 10 LIST: 10 20 dequeued 10 LIST: 20 LIST: 20 30 dequeued 20 LIST: 30 dequeued 30 LIST: UNDERFLOW LIST:
polynomial_linked_list.ctested ✓ 200/200Checked against: TS runPolyAdd — every term of the sum (cancelled terms dropped) · Lesson: Polynomials using linked lists
Open the lesson: Polynomials using linked lists →
/* Polynomial addition using linked lists — KTU PCCST303, Module 2 (KTU model Q12a, Nov 2025 Q11a)
* Each node holds one term: coef, exp and a link to the next (smaller-exponent) term.
* Input : nA coef exp ... nB coef exp ... (decreasing exponents)
* Output: "SUM: coef exp coef exp ..." */
#include <stdio.h>
#include <stdlib.h>
struct node {
int coef, exp;
struct node *next;
};
/* append a term at the end of the list whose last node is *tail */
void attach(int coef, int exp, struct node **head, struct node **tail) {
struct node *n = malloc(sizeof *n);
if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
n->coef = coef; n->exp = exp; n->next = NULL;
if (*head == NULL) *head = n; else (*tail)->next = n;
*tail = n;
}
struct node *readPoly(int *ok) {
struct node *head = NULL, *tail = NULL;
int n, c, e;
if (scanf("%d", &n) != 1 || n < 0) { *ok = 0; return NULL; }
while (n-- > 0) {
if (scanf("%d %d", &c, &e) != 2) { *ok = 0; break; }
attach(c, e, &head, &tail);
}
return head;
}
struct node *addPoly(struct node *p, struct node *q) {
struct node *head = NULL, *tail = NULL;
while (p != NULL && q != NULL) {
if (p->exp > q->exp) { attach(p->coef, p->exp, &head, &tail); p = p->next; }
else if (p->exp < q->exp) { attach(q->coef, q->exp, &head, &tail); q = q->next; }
else {
int sum = p->coef + q->coef;
if (sum != 0) attach(sum, p->exp, &head, &tail);
p = p->next; q = q->next;
}
}
for (; p != NULL; p = p->next) attach(p->coef, p->exp, &head, &tail);
for (; q != NULL; q = q->next) attach(q->coef, q->exp, &head, &tail);
return head;
}
void freeList(struct node *p) { while (p != NULL) { struct node *t = p; p = p->next; free(t); } }
int main(void) {
int ok = 1;
struct node *a = readPoly(&ok), *b = readPoly(&ok), *c, *p;
if (!ok) { printf("BAD INPUT\n"); freeList(a); freeList(b); return 1; }
c = addPoly(a, b);
printf("SUM:");
for (p = c; p != NULL; p = p->next) printf(" %d %d", p->coef, p->exp);
printf("\n");
freeList(a); freeList(b); freeList(c);
return 0;
}
Sample run · model Q12a · real output from gcc
Input (stdin)
4 2 3 5 2 -4 1 5 0 4 4 3 2 2 3 1 -6 0
Output (stdout)
SUM: 6 3 7 2 -1 1 -1 0
memory_allocation.ctested ✓ 720/720Checked against: TS runMemory — final placement, waiting list and every segment (first/best/worst × split/fixed, with free, coalescing and compaction) · Lesson: Memory allocation: first-fit, best-fit, worst-fit
Open the lesson: Memory allocation: first-fit, best-fit, worst-fit →
/* First-fit, best-fit and worst-fit allocation — KTU PCCST303, Module 2
* (KTU Nov 2025 Q12a, May 2026 Q12a)
* Memory is a list of segments; each segment belongs to a block and is either a hole or
* holds one process. Requests are served in order; a request that fits nowhere waits.
* split mode : the leftover part of a hole stays a (smaller) hole — variable partitions
* fixed mode : the whole hole goes to the process, leftover is wasted — fixed partitions
* Input : n size1 ... sizen scheme F|B|W mode S|X then commands until EOF:
* A size (allocate; processes are named P1, P2, ... in request order)
* F k (free process Pk: coalesce with neighbouring holes, retry waiting ones)
* C (compact: move all processes to the start, one big hole at the end)
* Output: "P<k> -> <block index>" lines (0-based), "WAIT: P..", and the final segments. */
#include <stdio.h>
#include <string.h>
#define MAXS 64
struct seg { int block, size, owner, waste; }; /* owner 0 = hole */
struct seg m[MAXS];
int nseg, nblocks, blockSize[16];
char scheme, mode;
int waitPid[32], waitSize[32], nwait;
int placedBlock[33]; /* -1 = not in memory */
/* index of the hole chosen by the current scheme, or -1 */
int chooseHole(int r) {
int i, pick = -1;
for (i = 0; i < nseg; i++) {
if (m[i].owner != 0 || m[i].size < r) continue;
if (pick == -1) pick = i;
else if (scheme == 'B' && m[i].size < m[pick].size) pick = i; /* smallest that fits */
else if (scheme == 'W' && m[i].size > m[pick].size) pick = i; /* largest */
if (scheme == 'F') break; /* first that fits */
}
return pick;
}
void place(int pid, int r, int i) {
int left = m[i].size - r;
if (mode == 'S' && left > 0) { /* split: process part + new hole */
memmove(&m[i + 2], &m[i + 1], (size_t)(nseg - i - 1) * sizeof m[0]);
nseg++;
m[i + 1].block = m[i].block; m[i + 1].size = left; m[i + 1].owner = 0; m[i + 1].waste = 0;
m[i].size = r;
} else if (mode == 'X') { m[i].size = r; m[i].waste = left; } /* rest of the block is wasted */
m[i].owner = pid;
placedBlock[pid] = m[i].block;
}
void removeSeg(int i) { memmove(&m[i], &m[i + 1], (size_t)(nseg - i - 1) * sizeof m[0]); nseg--; }
void retryWaiting(int onlyFirstFitHole) {
int k, still = 0;
for (k = 0; k < nwait; k++) {
int i;
if (onlyFirstFitHole) { for (i = 0; i < nseg && !(m[i].owner == 0 && m[i].size >= waitSize[k]); i++) { } if (i == nseg) i = -1; }
else i = chooseHole(waitSize[k]);
if (i < 0) { waitPid[still] = waitPid[k]; waitSize[still] = waitSize[k]; still++; }
else place(waitPid[k], waitSize[k], i);
}
nwait = still;
}
void freeProcess(int pid) {
int i;
for (i = 0; i < nseg && m[i].owner != pid; i++) { }
if (i == nseg) { printf("P%d is not in memory\n", pid); return; }
m[i].owner = 0; m[i].size += m[i].waste; m[i].waste = 0;
placedBlock[pid] = -1;
if (i + 1 < nseg && m[i + 1].owner == 0 && m[i + 1].block == m[i].block) { m[i].size += m[i + 1].size; removeSeg(i + 1); }
if (i > 0 && m[i - 1].owner == 0 && m[i - 1].block == m[i].block) { m[i - 1].size += m[i].size; removeSeg(i); }
retryWaiting(0);
}
void compact(void) {
int i, k = 0, total = 0, used = 0;
for (i = 0; i < nblocks; i++) total += blockSize[i];
for (i = 0; i < nseg; i++)
if (m[i].owner != 0) {
m[k] = m[i]; m[k].size += m[k].waste; m[k].waste = 0; m[k].block = 0;
used += m[k].size; placedBlock[m[k].owner] = 0; k++;
}
nseg = k;
if (total > used) { m[nseg].block = 0; m[nseg].size = total - used; m[nseg].owner = 0; m[nseg].waste = 0; nseg++; }
nblocks = 1; blockSize[0] = total;
{ /* after compaction memory is one variable region: waiting processes take what they
need from the big hole (split), first come first served */
char saved = mode;
mode = 'S';
retryWaiting(1);
mode = saved;
}
}
int main(void) {
char cmd[4], s[4], md[4];
int i, x, pid = 0;
if (scanf("%d", &nblocks) != 1 || nblocks < 1 || nblocks > 10) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < nblocks; i++) {
if (scanf("%d", &blockSize[i]) != 1) { printf("BAD INPUT\n"); return 1; }
m[i].block = i; m[i].size = blockSize[i]; m[i].owner = 0; m[i].waste = 0;
}
nseg = nblocks;
if (scanf("%3s %3s", s, md) != 2) { printf("BAD INPUT\n"); return 1; }
scheme = s[0]; mode = md[0];
for (i = 0; i < 33; i++) placedBlock[i] = -1;
while (scanf("%3s", cmd) == 1) {
if (cmd[0] == 'A' && scanf("%d", &x) == 1 && pid < 32) {
int h = chooseHole(x);
pid++;
if (h < 0) { waitPid[nwait] = pid; waitSize[nwait] = x; nwait++; }
else place(pid, x, h);
} else if (cmd[0] == 'F' && scanf("%d", &x) == 1) freeProcess(x);
else if (cmd[0] == 'C') compact();
else { printf("BAD COMMAND\n"); return 1; }
}
for (i = 1; i <= pid; i++) if (placedBlock[i] >= 0) printf("P%d -> %d\n", i, placedBlock[i]);
printf("WAIT:");
for (i = 0; i < nwait; i++) printf(" P%d", waitPid[i]);
printf("\n");
for (i = 0; i < nseg; i++) printf("SEG: %d %d %d %d\n", m[i].block, m[i].size, m[i].owner, m[i].waste);
return 0;
}
Sample run · May 2026 Q12a, best fit · real output from gcc
Input (stdin)
6 200 400 600 500 300 250 B S A 357 A 210 A 468 A 491
Output (stdout)
P1 -> 1 P2 -> 5 P3 -> 3 P4 -> 2 WAIT: SEG: 0 200 0 0 SEG: 1 357 1 0 SEG: 1 43 0 0 SEG: 2 491 4 0 SEG: 2 109 0 0 SEG: 3 468 3 0 SEG: 3 32 0 0 SEG: 4 300 0 0 SEG: 5 210 2 0 SEG: 5 40 0 0
Module 3
bst.ctested ✓ 200/200Checked against: TS runBST — result of every operation (search comparisons, traversals) and the exact tree shape after it · Lesson: Tree operations and traversals
Open the lesson: Tree operations and traversals →
/* Binary search tree — KTU PCCST303, Module 3 (KTU Nov 2025 Q13a, model Q14b)
* Left subtree < node < right subtree. Duplicates are ignored.
* Delete with two children: copy the inorder successor (smallest key of the right
* subtree) into the node, then delete the successor.
* Commands: I x | D x | S x | IN | PRE | POST | LEVEL
* After every command: optional result line, then "TREE: " + parenthesised form,
* e.g. 35(12(,30),47) — key(left,right), leaves written alone. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int key;
struct node *left, *right;
};
struct node *root = NULL;
struct node *newNode(int x) {
struct node *n = malloc(sizeof *n);
if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
n->key = x; n->left = n->right = NULL;
return n;
}
void insert(int x) {
struct node **p = &root;
while (*p != NULL) {
if (x == (*p)->key) { printf("duplicate ignored\n"); return; }
p = x < (*p)->key ? &(*p)->left : &(*p)->right;
}
*p = newNode(x);
}
void search(int x) {
struct node *p = root;
int comparisons = 0;
while (p != NULL) {
comparisons++;
if (x == p->key) { printf("found after %d comparison%s\n", comparisons, comparisons > 1 ? "s" : ""); return; }
p = x < p->key ? p->left : p->right;
}
printf("not found\n");
}
void deleteKey(int x) {
struct node **p = &root, *t;
while (*p != NULL && (*p)->key != x) p = x < (*p)->key ? &(*p)->left : &(*p)->right;
if (*p == NULL) { printf("not found\n"); return; }
t = *p;
if (t->left != NULL && t->right != NULL) { /* case 3: two children */
struct node **s = &t->right;
while ((*s)->left != NULL) s = &(*s)->left; /* inorder successor */
t->key = (*s)->key;
t = *s;
*s = t->right; /* successor has no left child */
} else *p = t->left != NULL ? t->left : t->right; /* cases 1 and 2 */
free(t);
printf("deleted %d\n", x);
}
void inorder(struct node *t) { if (t) { inorder(t->left); printf(" %d", t->key); inorder(t->right); } }
void preorder(struct node *t) { if (t) { printf(" %d", t->key); preorder(t->left); preorder(t->right); } }
void postorder(struct node *t) { if (t) { postorder(t->left); postorder(t->right); printf(" %d", t->key); } }
void levelorder(void) {
struct node *q[64];
int front = 0, rear = 0;
if (root) q[rear++] = root;
while (front < rear) {
struct node *t = q[front++];
printf(" %d", t->key);
if (t->left) q[rear++] = t->left;
if (t->right) q[rear++] = t->right;
}
}
void show(struct node *t) {
if (t == NULL) return;
printf("%d", t->key);
if (t->left || t->right) { printf("("); show(t->left); printf(","); show(t->right); printf(")"); }
}
void freeTree(struct node *t) { if (t) { freeTree(t->left); freeTree(t->right); free(t); } }
int main(void) {
char cmd[8];
int x;
while (scanf("%7s", cmd) == 1) {
if (strcmp(cmd, "I") == 0 && scanf("%d", &x) == 1) insert(x);
else if (strcmp(cmd, "D") == 0 && scanf("%d", &x) == 1) deleteKey(x);
else if (strcmp(cmd, "S") == 0 && scanf("%d", &x) == 1) search(x);
else if (strcmp(cmd, "IN") == 0) { printf("inorder:"); inorder(root); printf("\n"); }
else if (strcmp(cmd, "PRE") == 0) { printf("preorder:"); preorder(root); printf("\n"); }
else if (strcmp(cmd, "POST") == 0) { printf("postorder:"); postorder(root); printf("\n"); }
else if (strcmp(cmd, "LEVEL") == 0) { printf("levelorder:"); levelorder(); printf("\n"); }
else { printf("BAD COMMAND\n"); break; }
printf("TREE: "); show(root); printf("\n");
}
freeTree(root);
return 0;
}
Sample run · Nov 2025 Q13a · real output from gcc
Input (stdin)
I 35 I 12 I 47 I 36 I 52 I 30 I 25 I 49 IN D 30 D 47
Output (stdout)
TREE: 35 TREE: 35(12,) TREE: 35(12,47) TREE: 35(12,47(36,)) TREE: 35(12,47(36,52)) TREE: 35(12(,30),47(36,52)) TREE: 35(12(,30(25,)),47(36,52)) TREE: 35(12(,30(25,)),47(36,52(49,))) inorder: 12 25 30 35 36 47 49 52 TREE: 35(12(,30(25,)),47(36,52(49,))) deleted 30 TREE: 35(12(,25),47(36,52(49,))) deleted 47 TREE: 35(12(,25),49(36,52))
binary_heap.ctested ✓ 199/199Checked against: TS runHeap (max and min) — array after every build / insert / delete and every removed root · Lesson: Binary tree representation
Open the lesson: Binary tree representation →
/* Binary heap and priority queue (array) — KTU PCCST303, Module 3 (KTU May 2026 Q16b)
* Root at index 0; children of i are 2i+1 and 2i+2; parent is (i-1)/2.
* First token: MAX or MIN. Commands:
* B n k1 .. kn build a heap bottom-up from the keys (O(n))
* I x insert: put x at the end and sift it up
* D delete the root: move the last key to the root and sift it down
* After every command: optional result line, then "HEAP: a[0] a[1] ...". */
#include <stdio.h>
#include <string.h>
#define CAP 100
int a[CAP], n = 0, isMax = 1;
int beats(int x, int y) { return isMax ? x > y : x < y; } /* should x be above y? */
void swap(int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
void siftUp(int i) {
while (i > 0 && beats(a[i], a[(i - 1) / 2])) { swap(i, (i - 1) / 2); i = (i - 1) / 2; }
}
void siftDown(int i) {
for (;;) {
int l = 2 * i + 1, r = 2 * i + 2, b = i;
if (l < n && beats(a[l], a[b])) b = l;
if (r < n && beats(a[r], a[b])) b = r;
if (b == i) return;
swap(i, b);
i = b;
}
}
void insert(int x) {
if (n == CAP) { printf("OVERFLOW\n"); return; }
a[n] = x;
siftUp(n++);
}
void deleteRoot(void) {
if (n == 0) { printf("UNDERFLOW\n"); return; }
printf("removed %d\n", a[0]);
a[0] = a[--n];
siftDown(0);
}
void build(void) { int i; for (i = n / 2 - 1; i >= 0; i--) siftDown(i); }
int main(void) {
char kind[4], cmd[4];
int i, k, x;
if (scanf("%3s", kind) != 1) return 1;
isMax = strcmp(kind, "MIN") != 0;
while (scanf("%3s", cmd) == 1) {
if (cmd[0] == 'B' && scanf("%d", &k) == 1 && k >= 0 && k <= CAP) {
n = 0;
for (i = 0; i < k && scanf("%d", &x) == 1; i++) a[n++] = x;
build();
} else if (cmd[0] == 'I' && scanf("%d", &x) == 1) insert(x);
else if (cmd[0] == 'D') deleteRoot();
else { printf("BAD COMMAND\n"); break; }
printf("HEAP:");
for (i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
return 0;
}
Sample run · May 2026 Q16b · real output from gcc
Input (stdin)
MAX B 7 20 12 30 25 18 8 24 D
Output (stdout)
HEAP: 30 25 24 12 18 8 20 removed 30 HEAP: 25 20 24 12 18 8
expression_tree.ctested ✓ 400/400Checked against: TS runExpressionTree — preorder (prefix) and postorder of the built tree · Lesson: Expression trees
Open the lesson: Expression trees →
/* Expression tree from an infix expression — KTU PCCST303, Module 3 (KTU Nov 2025 Q6, model Q13b)
* Step 1: infix -> postfix with an operator stack (^ is right-associative, highest).
* Step 2: scan the postfix: an operand becomes a one-node tree; an operator pops the
* right subtree, then the left subtree, and becomes their parent.
* Then preorder = prefix form, postorder = postfix form.
* Input : one valid infix expression per line (letters, whole numbers, + - * / % ^ ( )).
* Output: "PREFIX: ..." and "POSTFIX: ..." for each line. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXTOK 128
struct node {
char tok[12];
struct node *left, *right;
};
int prec(char c) { return c == '^' ? 3 : (c == '*' || c == '/' || c == '%') ? 2 : (c == '+' || c == '-') ? 1 : 0; }
int isOp(const char *t) { return t[1] == '\0' && prec(t[0]) > 0; }
/* split into tokens: numbers, single letters, operators and brackets */
int tokenize(const char *s, char tok[][12]) {
int n = 0;
while (*s && n < MAXTOK) {
if (isspace((unsigned char)*s)) { s++; continue; }
if (isdigit((unsigned char)*s)) {
int k = 0;
while (*s == '0' && isdigit((unsigned char)s[1])) s++; /* "007" is 7 */
while (isdigit((unsigned char)*s) && k < 10) tok[n][k++] = *s++;
tok[n++][k] = '\0';
} else { tok[n][0] = *s++; tok[n++][1] = '\0'; }
}
return n;
}
int toPostfix(char in[][12], int n, char out[][12]) {
char stack[MAXTOK];
int top = -1, k = 0, i;
for (i = 0; i < n; i++) {
char c = in[i][0];
if (isalnum((unsigned char)c)) strcpy(out[k++], in[i]);
else if (c == '(') stack[++top] = c;
else if (c == ')') {
while (top >= 0 && stack[top] != '(') { out[k][0] = stack[top--]; out[k++][1] = '\0'; }
top--; /* discard '(' */
} else {
/* pop while the stack top has higher precedence, or equal and left-associative */
while (top >= 0 && stack[top] != '(' && (prec(stack[top]) > prec(c) || (prec(stack[top]) == prec(c) && c != '^'))) {
out[k][0] = stack[top--]; out[k++][1] = '\0';
}
stack[++top] = c;
}
}
while (top >= 0) { out[k][0] = stack[top--]; out[k++][1] = '\0'; }
return k;
}
struct node *build(char post[][12], int n) {
struct node *stack[MAXTOK];
int top = -1, i;
for (i = 0; i < n; i++) {
struct node *t = malloc(sizeof *t);
if (t == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
strcpy(t->tok, post[i]);
t->left = t->right = NULL;
if (isOp(post[i])) { t->right = stack[top--]; t->left = stack[top--]; } /* right first! */
stack[++top] = t;
}
return stack[top];
}
void preorder(struct node *t) { if (t) { printf(" %s", t->tok); preorder(t->left); preorder(t->right); } }
void postorder(struct node *t) { if (t) { postorder(t->left); postorder(t->right); printf(" %s", t->tok); } }
void freeTree(struct node *t) { if (t) { freeTree(t->left); freeTree(t->right); free(t); } }
int main(void) {
char line[512], in[MAXTOK][12], post[MAXTOK][12];
while (fgets(line, sizeof line, stdin)) {
int n = tokenize(line, in), m;
struct node *root;
if (n == 0) continue;
m = toPostfix(in, n, post);
root = build(post, m);
printf("PREFIX:"); preorder(root); printf("\n");
printf("POSTFIX:"); postorder(root); printf("\n");
freeTree(root);
}
return 0;
}
Sample run · Nov 2025 Q6 and model Q13b · real output from gcc
Input (stdin)
(A+B*C)-D-E*F-(G-H/I) a+b*c/d+(e*f+g)*h
Output (stdout)
PREFIX: - - - + A * B C D * E F - G / H I POSTFIX: A B C * + D - E F * - G H I / - - PREFIX: + + a / * b c d * + * e f g h POSTFIX: a b c * d / + e f * g + h * +
graph_traversal.ctested ✓ 250/250Checked against: TS runGraph — BFS and DFS visit order (neighbours ascending) · Lesson: Graph representation
Open the lesson: Graph representation →
/* BFS and DFS on an adjacency matrix — KTU PCCST303, Module 3 (KTU Nov 2025 Q14a, May 2026 Q14a)
* Neighbours are taken in increasing vertex order, which makes the visit order unique —
* the convention KTU answer keys follow.
* Input : n m directed(0|1) then m edges "u v" (0..n-1) then the start vertex.
* Output: "BFS: ..." and "DFS: ..." (only vertices reachable from the start). */
#include <stdio.h>
#include <string.h>
#define MAXV 20
int adj[MAXV][MAXV], n, visited[MAXV];
void bfs(int s) {
int queue[MAXV], front = 0, rear = 0, u, v;
memset(visited, 0, sizeof visited);
visited[s] = 1;
queue[rear++] = s; /* mark when ENQUEUED, not when dequeued */
printf("BFS:");
while (front < rear) {
u = queue[front++];
printf(" %d", u);
for (v = 0; v < n; v++)
if (adj[u][v] && !visited[v]) { visited[v] = 1; queue[rear++] = v; }
}
printf("\n");
}
void dfs(int u) {
int v;
visited[u] = 1;
printf(" %d", u);
for (v = 0; v < n; v++)
if (adj[u][v] && !visited[v]) dfs(v); /* go deeper before trying the next neighbour */
}
int main(void) {
int m, directed, u, v, s, i;
if (scanf("%d %d %d", &n, &m, &directed) != 3 || n < 1 || n > MAXV) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < m; i++) {
if (scanf("%d %d", &u, &v) != 2 || u < 0 || v < 0 || u >= n || v >= n) { printf("BAD INPUT\n"); return 1; }
adj[u][v] = 1;
if (!directed) adj[v][u] = 1;
}
if (scanf("%d", &s) != 1 || s < 0 || s >= n) { printf("BAD INPUT\n"); return 1; }
bfs(s);
memset(visited, 0, sizeof visited);
printf("DFS:"); dfs(s); printf("\n");
return 0;
}
Sample run · lesson graph, start 0 · real output from gcc
Input (stdin)
5 6 0 0 1 0 2 1 2 1 3 2 4 3 4 0
Output (stdout)
BFS: 0 1 2 3 4 DFS: 0 1 2 4 3
dijkstra.ctested ✓ 250/250Checked against: TS runGraph (Dijkstra) — final distance and predecessor of every vertex · Lesson: Single source all destinations (Dijkstra)
Open the lesson: Single source all destinations (Dijkstra) →
/* Dijkstra's single-source shortest paths — KTU PCCST303, Module 3 (May 2026 Q13b, model Q14a)
* Repeatedly lock the unfinished vertex with the smallest tentative distance (ties: the
* smaller vertex number), then relax its outgoing edges. Needs non-negative weights.
* Input : n m directed(0|1) then m edges "u v w" then the source.
* Output: "v dist pred" for every vertex (INF / -1 when unreachable). */
#include <stdio.h>
#define MAXV 20
#define INF 1000000000
int cost[MAXV][MAXV], hasEdge[MAXV][MAXV];
int main(void) {
int n, m, directed, u, v, w, s, i, k;
int dist[MAXV], pred[MAXV], done[MAXV];
if (scanf("%d %d %d", &n, &m, &directed) != 3 || n < 1 || n > MAXV) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < m; i++) {
if (scanf("%d %d %d", &u, &v, &w) != 3 || u < 0 || v < 0 || u >= n || v >= n || w < 0) { printf("BAD INPUT\n"); return 1; }
cost[u][v] = w; hasEdge[u][v] = 1;
if (!directed) { cost[v][u] = w; hasEdge[v][u] = 1; }
}
if (scanf("%d", &s) != 1 || s < 0 || s >= n) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < n; i++) { dist[i] = INF; pred[i] = -1; done[i] = 0; }
dist[s] = 0;
for (k = 0; k < n; k++) {
u = -1;
for (i = 0; i < n; i++) /* choose: smallest dist, not done */
if (!done[i] && dist[i] < INF && (u == -1 || dist[i] < dist[u])) u = i;
if (u == -1) break; /* the rest is unreachable */
done[u] = 1;
for (v = 0; v < n; v++) /* relax every edge u -> v */
if (hasEdge[u][v] && !done[v] && dist[u] + cost[u][v] < dist[v]) {
dist[v] = dist[u] + cost[u][v];
pred[v] = u;
}
}
for (i = 0; i < n; i++) {
if (dist[i] == INF) printf("%d INF -1\n", i);
else printf("%d %d %d\n", i, dist[i], pred[i]);
}
return 0;
}
Sample run · A..E = 0..4, source A · real output from gcc
Input (stdin)
5 6 1 0 1 4 0 2 1 2 1 2 1 3 1 2 3 5 3 4 3 0
Output (stdout)
0 0 -1 1 3 2 2 1 0 3 4 1 4 7 3
Module 4
insertion_sort.ctested ✓ 132/132Checked against: TS engine "insertion" — every intermediate pass · Lesson: Insertion sort
Open the lesson: Insertion sort →
/* Insertion sort — KTU PCCST303, Module 4
* Input : n followed by n integers
* Output: the array after every pass, then the sorted array. */
#include <stdio.h>
#define MAX 100
void printArray(const char *label, int a[], int n) {
printf("%s:", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
void insertionSort(int a[], int n) {
for (int i = 1; i < n; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) { /* shift larger elements right */
a[j + 1] = a[j];
j--;
}
a[j + 1] = key; /* drop key into the gap */
printArray("PASS", a, n);
}
}
int main(void) {
int n, a[MAX];
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++)
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); return 1; }
insertionSort(a, n);
printArray("SORTED", a, n);
return 0;
}
Sample run · KTU PYQ input · real output from gcc
Input (stdin)
7 34 21 3 121 342 65 44
Output (stdout)
PASS: 21 34 3 121 342 65 44 PASS: 3 21 34 121 342 65 44 PASS: 3 21 34 121 342 65 44 PASS: 3 21 34 121 342 65 44 PASS: 3 21 34 65 121 342 44 PASS: 3 21 34 44 65 121 342 SORTED: 3 21 34 44 65 121 342
heap_sort.ctested ✓ 132/132Checked against: TS engine "heap" — every intermediate pass · Lesson: Heap sort
/* Heap sort using a max-heap — KTU PCCST303, Module 4
* 0-based array: children of i are 2i+1 and 2i+2.
* Input : n followed by n integers
* Output: the heap after building, the array after every extraction,
* then the sorted array. */
#include <stdio.h>
#define MAX 100
void printArray(const char *label, int a[], int n) {
printf("%s:", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
/* sift a[i] down within a[0..size-1] */
void heapify(int a[], int i, int size) {
while (1) {
int largest = i, l = 2 * i + 1, r = 2 * i + 2;
if (l < size && a[l] > a[largest]) largest = l;
if (r < size && a[r] > a[largest]) largest = r;
if (largest == i) break;
swap(&a[i], &a[largest]);
i = largest;
}
}
void heapSort(int a[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) /* build max-heap bottom-up */
heapify(a, i, n);
printArray("PASS", a, n);
for (int end = n - 1; end >= 1; end--) {
swap(&a[0], &a[end]); /* max to its final place */
heapify(a, 0, end);
printArray("PASS", a, n);
}
}
int main(void) {
int n, a[MAX];
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++)
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); return 1; }
heapSort(a, n);
printArray("SORTED", a, n);
return 0;
}
Sample run · KTU PYQ input · real output from gcc
Input (stdin)
7 20 12 30 25 18 8 24
Output (stdout)
PASS: 30 25 24 12 18 8 20 PASS: 25 20 24 12 18 8 30 PASS: 24 20 8 12 18 25 30 PASS: 20 18 8 12 24 25 30 PASS: 18 12 8 20 24 25 30 PASS: 12 8 18 20 24 25 30 PASS: 8 12 18 20 24 25 30 SORTED: 8 12 18 20 24 25 30
radix_sort.ctested ✓ 132/132Checked against: TS engine "radix" — every intermediate pass · Lesson: Radix sort
/* Radix sort (LSD, base 10, bucket queues) — KTU PCCST303, Module 4
* Works for non-negative integers.
* Input : n followed by n integers
* Output: the array after every digit pass, then the sorted array. */
#include <stdio.h>
#define MAX 100
void printArray(const char *label, int a[], int n) {
printf("%s:", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
void radixSort(int a[], int n) {
int bucket[10][MAX], count[10];
int max = 0;
for (int i = 0; i < n; i++) if (a[i] > max) max = a[i];
int passes = 1;
for (int m = max; m >= 10; m /= 10) passes++; /* digits in max */
for (int p = 0, place = 1; p < passes; p++, place *= 10) {
for (int b = 0; b < 10; b++) count[b] = 0;
for (int i = 0; i < n; i++) { /* distribute */
int d = (a[i] / place) % 10;
bucket[d][count[d]++] = a[i];
}
int k = 0;
for (int b = 0; b < 10; b++) /* collect 0..9 */
for (int i = 0; i < count[b]; i++) a[k++] = bucket[b][i];
printArray("PASS", a, n);
}
}
int main(void) {
int n, a[MAX];
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1 || a[i] < 0) { printf("Invalid input\n"); return 1; }
}
radixSort(a, n);
printArray("SORTED", a, n);
return 0;
}
Sample run · KTU PYQ input · real output from gcc
Input (stdin)
7 341 22 33 122 42 5 4
Output (stdout)
PASS: 341 22 122 42 33 4 5 PASS: 4 5 22 122 33 341 42 PASS: 4 5 22 33 42 122 341 SORTED: 4 5 22 33 42 122 341
selection_sort.ctested ✓ 228/228Checked against: exact output text (prompts + sorted array) for selection sort; edge cases, duplicates, negatives, PYQ inputs and full 100-element arrays · Lesson: Selection sort
Open the lesson: Selection sort →
/* Selection Sort — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
int main()
{
int a[100], n, i, j, min, temp;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n - 1; i++) { /* i = 0 to n-2 */
min = i;
for (j = i + 1; j < n; j++) /* find the smallest in a[i..n-1] */
if (a[j] < a[min])
min = j;
temp = a[i]; /* swap a[i] and a[min] */
a[i] = a[min];
a[min] = temp;
}
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 8 Enter array elements: 45 33 56 22 76 78 40 30 Sorted array: 22 30 33 40 45 56 76 78
Bold = what you type. Everything else is printed by the program.
quick_sort_first_pivot.ctested ✓ 228/228Checked against: exact output text (prompts + sorted array) for quick sort (first-element pivot); edge cases, duplicates, negatives, PYQ inputs and full 100-element arrays · Lesson: Quick sort
/* Quick Sort, first element as pivot — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
void quickSort(int a[], int low, int high)
{
int pivot, i, j, temp;
if (low < high) {
pivot = a[low]; /* first element is the pivot */
i = low + 1;
j = high;
while (i <= j) {
while (i <= high && a[i] <= pivot) /* check i <= high first */
i++;
while (a[j] > pivot) /* stops at a[low] at worst */
j--;
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[low]; /* put the pivot in its place */
a[low] = a[j];
a[j] = temp;
quickSort(a, low, j - 1);
quickSort(a, j + 1, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
quickSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 10 Enter array elements: 45 36 12 65 24 11 44 54 17 33 Sorted array: 11 12 17 24 33 36 44 45 54 65
Bold = what you type. Everything else is printed by the program.
quick_sort_last_pivot.ctested ✓ 228/228Checked against: exact output text (prompts + sorted array) for quick sort (last-element pivot); edge cases, duplicates, negatives, PYQ inputs and full 100-element arrays · Lesson: Quick sort
/* Quick Sort, last element as pivot (Lomuto partition) — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
int partition(int a[], int low, int high)
{
int pivot, i, j, temp;
pivot = a[high]; /* last element is the pivot */
i = low - 1;
for (j = low; j < high; j++) {
if (a[j] <= pivot) {
i++;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i + 1]; /* put the pivot in its place */
a[i + 1] = a[high];
a[high] = temp;
return i + 1;
}
void quickSort(int a[], int low, int high)
{
int p;
if (low < high) {
p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
quickSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 10 Enter array elements: 45 36 12 65 24 11 44 54 17 33 Sorted array: 11 12 17 24 33 36 44 45 54 65
Bold = what you type. Everything else is printed by the program.
merge_sort.ctested ✓ 228/228Checked against: exact output text (prompts + sorted array) for merge sort; edge cases, duplicates, negatives, PYQ inputs and full 100-element arrays · Lesson: Merge sort
/* Merge Sort — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
void merge(int a[], int low, int mid, int high)
{
int temp[100], i, j, k;
i = low;
j = mid + 1;
k = low;
while (i <= mid && j <= high) { /* copy the smaller element */
if (a[i] <= a[j]) {
temp[k] = a[i];
i++;
}
else {
temp[k] = a[j];
j++;
}
k++;
}
while (i <= mid) { /* rest of the first half */
temp[k] = a[i];
i++;
k++;
}
while (j <= high) { /* rest of the second half */
temp[k] = a[j];
j++;
k++;
}
for (i = low; i <= high; i++) /* copy temp back to a */
a[i] = temp[i];
}
void mergeSort(int a[], int low, int high)
{
int mid;
if (low < high) {
mid = (low + high) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
mergeSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 8 Enter array elements: 45 33 56 22 76 78 40 30 Sorted array: 22 30 33 40 45 56 76 78
Bold = what you type. Everything else is printed by the program.
binary_search.ctested ✓ 213/213Checked against: exact output text; found position = TS binarySearch index + 1 (distinct keys), reference model of the Step algorithm (duplicates) · Lesson: Binary search
Open the lesson: Binary search →
/* Binary Search — KTU PCCST303, Module 4 (lab-record style)
* The elements must be entered in ascending order. */
#include <stdio.h>
int main()
{
int a[100], n, i, key, low, high, mid, found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements in ascending order:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter element to search: ");
scanf("%d", &key);
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
printf("Element found at position %d\n", mid + 1);
found = 1;
break;
}
else if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
if (found == 0)
printf("Element not found\n");
return 0;
}
Sample input / output · search for 44 · real run, compiled with gcc
Enter number of elements: 8 Enter array elements in ascending order: 4 11 17 24 33 44 54 65 Enter element to search: 44 Element found at position 6
Bold = what you type. Everything else is printed by the program.
linear_search.ctested ✓ 150/150Checked against: TS linearSearch — result index and comparison count · Lesson: Linear search
Open the lesson: Linear search →
/* Linear search — KTU PCCST303, Module 4
* Input : n, then n integers, then the key
* Output: index of the first occurrence (-1 if absent) and comparisons. */
#include <stdio.h>
#define MAX 100
int linearSearch(int a[], int n, int key, int *comparisons) {
*comparisons = 0;
for (int i = 0; i < n; i++) {
(*comparisons)++;
if (a[i] == key) return i;
}
return -1;
}
int main(void) {
int n, a[MAX], key, c;
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++)
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); return 1; }
if (scanf("%d", &key) != 1) { printf("Invalid key\n"); return 1; }
int idx = linearSearch(a, n, key, &c);
printf("RESULT: %d\nCOMPARISONS: %d\n", idx, c);
return 0;
}
Sample run · search for 22 · real output from gcc
Input (stdin)
8 45 33 56 22 76 78 40 30 22
Output (stdout)
RESULT: 3 COMPARISONS: 4
hashing_open_addressing.ctested ✓ 246/246Checked against: TS runHashOps — final table incl. tombstones (linear, quadratic, double) · Lesson: Collision resolution: linear probing, quadratic probing, double hashing
Open the lesson: Collision resolution: linear probing, quadratic probing, double hashing →
/* Hashing with open addressing — KTU PCCST303, Module 4
* h(k) = k mod m; collision resolution: linear, quadratic or double hashing
* (h2(k) = R - k mod R). Deletion uses tombstones (DELETED markers).
*
* Input : m method R then a list of operations until EOF:
* I key (insert) S key (search) D key (delete)
* method: 1 = linear, 2 = quadratic, 3 = double hashing
* Output: the final table, one line "TABLE: ..." ('-' empty, 'X' deleted). */
#include <stdio.h>
#define MAXM 101
#define EMPTY -1
#define DELETED -2
int table[MAXM], m, method, R;
int probe(int key, int i) {
int h = key % m;
if (method == 1) return (h + i) % m;
if (method == 2) return (h + i * i) % m;
return (h + i * (R - key % R)) % m;
}
int search(int key) {
for (int i = 0; i < m; i++) {
int s = probe(key, i);
if (table[s] == EMPTY) return -1; /* never-used slot: stop */
if (table[s] == key) return s; /* skip DELETED: continue */
}
return -1;
}
int insert(int key) {
int firstDeleted = -1;
for (int i = 0; i < m; i++) {
int s = probe(key, i);
if (table[s] == key) return -2; /* duplicate */
if (table[s] == DELETED) { if (firstDeleted < 0) firstDeleted = s; continue; }
if (table[s] == EMPTY) {
int t = (firstDeleted >= 0) ? firstDeleted : s;
table[t] = key;
return t;
}
}
if (firstDeleted >= 0) { table[firstDeleted] = key; return firstDeleted; }
return -1; /* no slot */
}
int delete(int key) {
int s = search(key);
if (s >= 0) table[s] = DELETED;
return s;
}
int main(void) {
char op; int key;
if (scanf("%d %d %d", &m, &method, &R) != 3 || m < 1 || m > MAXM || method < 1 || method > 3 || (method == 3 && R < 1)) {
printf("Invalid header\n"); return 1;
}
for (int i = 0; i < m; i++) table[i] = EMPTY;
while (scanf(" %c %d", &op, &key) == 2) {
if (key < 0) { printf("Invalid key\n"); return 1; }
if (op == 'I') printf("INSERT %d -> %d\n", key, insert(key));
else if (op == 'S') printf("SEARCH %d -> %d\n", key, search(key));
else if (op == 'D') printf("DELETE %d -> %d\n", key, delete(key));
}
printf("TABLE:");
for (int i = 0; i < m; i++) {
if (table[i] == EMPTY) printf(" -");
else if (table[i] == DELETED) printf(" X");
else printf(" %d", table[i]);
}
printf("\n");
return 0;
}
Sample run · m = 11, linear probing · real output from gcc
Input (stdin)
11 1 7 I 72 I 13 I 6 I 5 I 10 I 36 I 43 I 17
Output (stdout)
INSERT 72 -> 6 INSERT 13 -> 2 INSERT 6 -> 7 INSERT 5 -> 5 INSERT 10 -> 10 INSERT 36 -> 3 INSERT 43 -> 0 INSERT 17 -> 8 TABLE: 43 - 13 36 - 5 72 6 17 - 10
hashing_chaining.ctested ✓ 100/100Checked against: TS runHashOps (chaining) — every chain; ASan leak check · Lesson: Open hashing (separate chaining)
Open the lesson: Open hashing (separate chaining) →
/* Separate chaining (open hashing) — KTU PCCST303, Module 4
* h(k) = k mod m. New keys are appended at the tail of the chain.
* Input : m, then operations until EOF: I key | S key | D key
* Output: each chain as "i: k1 k2 ..." and frees all memory. */
#include <stdio.h>
#include <stdlib.h>
#define MAXM 101
struct node { int key; struct node *next; };
struct node *head[MAXM];
int m;
int search(int key) {
for (struct node *p = head[key % m]; p != NULL; p = p->next)
if (p->key == key) return 1;
return 0;
}
void insert(int key) {
if (search(key)) return; /* no duplicates */
struct node *t = malloc(sizeof *t);
if (t == NULL) { printf("Out of memory\n"); exit(1); }
t->key = key; t->next = NULL;
struct node **pp = &head[key % m];
while (*pp != NULL) pp = &(*pp)->next; /* walk to tail */
*pp = t;
}
void delete(int key) {
struct node **pp = &head[key % m];
while (*pp != NULL && (*pp)->key != key) pp = &(*pp)->next;
if (*pp != NULL) { struct node *dead = *pp; *pp = dead->next; free(dead); }
}
int main(void) {
char op; int key;
if (scanf("%d", &m) != 1 || m < 1 || m > MAXM) { printf("Invalid m\n"); return 1; }
while (scanf(" %c %d", &op, &key) == 2) {
if (key < 0) { printf("Invalid key\n"); return 1; }
if (op == 'I') insert(key);
else if (op == 'S') printf("SEARCH %d -> %s\n", key, search(key) ? "found" : "not found");
else if (op == 'D') delete(key);
}
for (int i = 0; i < m; i++) {
printf("%d:", i);
for (struct node *p = head[i]; p != NULL; p = p->next) printf(" %d", p->key);
printf("\n");
while (head[i] != NULL) { struct node *t = head[i]; head[i] = t->next; free(t); }
}
return 0;
}
Sample run · m = 11 · real output from gcc
Input (stdin)
11 I 72 I 13 I 6 I 5 I 10 I 36 I 43 I 17
Output (stdout)
0: 1: 2: 13 3: 36 4: 5: 5 6: 72 6 17 7: 8: 9: 10: 10 43
hash_functions.ctested ✓ 160/160Checked against: TS hashFunction — division, mid-square, folding, digit analysis · Lesson: Hashing and hash functions
Open the lesson: Hashing and hash functions →
/*
* Hash functions for keys 0..99999 and table size m (2..31):
* division h(k) = k mod m
* mid-square take the middle r digits of k*k, then mod m
* folding shift folding: split k into r-digit parts from the left, add, then mod m
* digit digit analysis: pick chosen digit positions (1-based, key zero-padded to width w)
* r = number of digits in (m - 1), i.e. how many digits an address needs.
*
* Input: m method [w count p1 p2 ...] (method: 1 division, 2 mid-square, 3 folding, 4 digit;
* w/count/positions only for method 4)
* then one key per line until end of input.
* Output: "HASH key home" for every key.
*/
#include <stdio.h>
#include <string.h>
static int num_digits(long long x) {
int d = 1;
while (x >= 10) { x /= 10; d++; }
return d;
}
static long long parse_digits(const char *s, int from, int len) {
long long v = 0;
for (int i = from; i < from + len; i++) v = v * 10 + (s[i] - '0');
return v;
}
static int division(long k, int m) { return (int)(k % m); }
static int mid_square(long k, int m) {
int r = num_digits(m - 1);
char s[32];
long long sq = (long long)k * k;
int len = snprintf(s, sizeof s, "%lld", sq);
if (len <= r) return (int)(sq % m); /* square is short: use all of it */
int start = (len - r) / 2; /* middle r digits */
return (int)(parse_digits(s, start, r) % m);
}
static int folding(long k, int m) {
int r = num_digits(m - 1);
char s[32];
int len = snprintf(s, sizeof s, "%ld", k);
long long sum = 0;
for (int i = 0; i < len; i += r) {
int part = (i + r <= len) ? r : len - i; /* last part may be shorter */
sum += parse_digits(s, i, part);
}
return (int)(sum % m);
}
static int digit_analysis(long k, int m, int width, const int *pos, int count) {
char s[32];
snprintf(s, sizeof s, "%0*ld", width, k); /* left-pad with zeros */
long long v = 0;
for (int i = 0; i < count; i++) v = v * 10 + (s[pos[i] - 1] - '0');
return (int)(v % m);
}
int main(void) {
int m, method, width = 0, count = 0, pos[8];
if (scanf("%d %d", &m, &method) != 2 || m < 2 || m > 31 || method < 1 || method > 4) return 1;
if (method == 4) {
if (scanf("%d %d", &width, &count) != 2 || width < 1 || width > 10 || count < 1 || count > 8) return 1;
for (int i = 0; i < count; i++)
if (scanf("%d", &pos[i]) != 1 || pos[i] < 1 || pos[i] > width) return 1;
}
long k;
while (scanf("%ld", &k) == 1) {
if (k < 0 || k > 99999) return 1;
if (method == 4 && num_digits(k) > width) return 1;
int h = method == 1 ? division(k, m)
: method == 2 ? mid_square(k, m)
: method == 3 ? folding(k, m)
: digit_analysis(k, m, width, pos, count);
printf("HASH %ld %d\n", k, h);
}
return 0;
}
Sample run · division method, m = 11 · real output from gcc
Input (stdin)
11 1 72 13 36
Output (stdout)
HASH 72 6 HASH 13 2 HASH 36 3