What a data structure is
Opens chatgpt.com in a new tab with a ready-made prompt for this topic.
Arrays: the one fact every MCQ tests
An array is a collection of elements of the same type stored in adjacent memory locations. Because the elements are adjacent, the address of any element can be computed directly:
Pointers in one slide
Dynamic memory allocation
stdlib.h.| Function | What it does | Example |
|---|---|---|
| malloc(size) | One block of size bytes; contents are garbage. Returns void *, or NULL if it fails. | int *a = malloc(n * sizeof(int)); |
| calloc(n, size) | n blocks of size bytes each, all set to zero | int *a = calloc(n, sizeof(int)); |
| realloc(p, size) | Resizes an existing block, keeping its contents | a = realloc(a, 2 * n * sizeof(int)); |
| free(p) | Returns the block to the heap | free(a); |
Opens chatgpt.com in a new tab with a ready-made prompt for this topic.
Creating arrays dynamically, and why it helps
How arrays can be created dynamically? Prove how it improves the performance of a program.
The problem with a fixed array
int a[1000]; fixes the size when the program is compiled. If the user enters only 10 numbers, 990 integers (3960 bytes with 4-byte ints) are wasted. If the user enters 1500, the array overflows.
A dynamic array asks for exactly n elements after n is known.
The program
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("How many numbers? ");
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int)); /* exactly n ints, decided at run time */
if (a == NULL) { printf("Not enough memory\n"); return 1; }
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
/* need room for 5 more? grow the same block instead of starting over */
int *t = (int *)realloc(a, (n + 5) * sizeof(int));
if (t != NULL) a = t;
long sum = 0;
for (int i = 0; i < n; i++) sum += a[i];
printf("Sum = %ld\n", sum);
free(a); /* give the memory back */
return 0;
}How it improves performance
| Point | Static int a[1000] | Dynamic malloc(n * sizeof(int)) |
|---|---|---|
| Memory for n = 10 | 4000 bytes | 40 bytes |
| Size decided | At compile time | At run time |
| Need more room | Impossible | realloc grows the block |
| When done | Held until the function returns | free releases it at once |
| Lifetime | Ends with the function | Lasts until free, so a function can return it |
Access time is the same, O(1) per element, in both cases. The gain is memory: the program uses exactly n×4 bytes instead of a worst-case guess, never overflows, and can return memory early. Less memory also means fewer cache misses and less paging on large inputs.
Booklet answer · Creating arrays dynamically, and why it helps
Creation: an array is created dynamically with malloc(n * sizeof(int)) or calloc(n, sizeof(int)) once n is known at run time. The returned pointer is used exactly like an array name (a[i]), resized with realloc, and released with free.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("How many numbers? ");
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int)); /* exactly n ints, decided at run time */
if (a == NULL) { printf("Not enough memory\n"); return 1; }
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
/* need room for 5 more? grow the same block instead of starting over */
int *t = (int *)realloc(a, (n + 5) * sizeof(int));
if (t != NULL) a = t;
long sum = 0;
for (int i = 0; i < n; i++) sum += a[i];
printf("Sum = %ld\n", sum);
free(a); /* give the memory back */
return 0;
}Improvement: a static int a[1000] takes 4000 bytes even for 10 values; the dynamic array takes 40. The size is not fixed in advance, so it can neither overflow nor waste space. realloc grows it when more data arrives, free returns memory immediately, and the block outlives the function that made it. Element access stays O(1).
Dynamic 2D matrices and matrix multiplication
What is dynamic memory allocation? Explain how dynamic memory allocation is applied for input matrices while performing matrix multiplication.
Discuss dynamic memory allocation in C and illustrate how to dynamically allocate memory for a 2D matrix. Also, provide a simple example of matrix multiplication.
Define a function to multiply two m x n matrices and return the resultant matrix.
A 2D matrix as an array of row pointers
For an r × c matrix, first allocate an array of r pointers (int **), then allocate each row of c integers. Then m[i][j] works exactly as for a normal 2D array.
The multiplication rule
A (m × n) times B (n × p) is defined only when the columns of A equal the rows of B. The result C is m × p, and
The complete program
#include <stdio.h>
#include <stdlib.h>
/* r x c matrix: an array of r row pointers, each row allocated separately */
int **alloc(int r, int c) {
int **m = (int **)malloc(r * sizeof(int *));
for (int i = 0; i < r; i++)
m[i] = (int *)calloc(c, sizeof(int)); /* calloc: every cell starts at 0 */
return m;
}
void release(int **m, int r) {
for (int i = 0; i < r; i++) free(m[i]);
free(m);
}
/* A is m x n, B is n x p, the result is m x p */
int **multiply(int **A, int **B, int m, int n, int p) {
int **C = alloc(m, p);
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++)
for (int k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
return C;
}
int main(void) {
int m, n, p;
printf("Rows of A, columns of A (= rows of B), columns of B: ");
scanf("%d %d %d", &m, &n, &p);
int **A = alloc(m, n), **B = alloc(n, p);
for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) scanf("%d", &A[i][j]);
for (int i = 0; i < n; i++) for (int j = 0; j < p; j++) scanf("%d", &B[i][j]);
int **C = multiply(A, B, m, n, p);
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) printf("%d ", C[i][j]);
printf("\n");
}
release(A, m); release(B, n); release(C, m);
return 0;
}The three nested loops run m⋅p⋅n times, so the time is O(mnp), or O(n3) for square matrices.
Booklet answer · Dynamic 2D matrices and matrix multiplication
Dynamic memory allocation reserves memory at run time from the heap using malloc, calloc and realloc (in stdlib.h), and returns it with free. For matrices whose sizes are read from the user, each matrix is allocated as an array of row pointers, each pointing to a row allocated separately, so no maximum size has to be fixed in advance.
#include <stdio.h>
#include <stdlib.h>
/* r x c matrix: an array of r row pointers, each row allocated separately */
int **alloc(int r, int c) {
int **m = (int **)malloc(r * sizeof(int *));
for (int i = 0; i < r; i++)
m[i] = (int *)calloc(c, sizeof(int)); /* calloc: every cell starts at 0 */
return m;
}
void release(int **m, int r) {
for (int i = 0; i < r; i++) free(m[i]);
free(m);
}
/* A is m x n, B is n x p, the result is m x p */
int **multiply(int **A, int **B, int m, int n, int p) {
int **C = alloc(m, p);
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++)
for (int k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
return C;
}
int main(void) {
int m, n, p;
printf("Rows of A, columns of A (= rows of B), columns of B: ");
scanf("%d %d %d", &m, &n, &p);
int **A = alloc(m, n), **B = alloc(n, p);
for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) scanf("%d", &A[i][j]);
for (int i = 0; i < n; i++) for (int j = 0; j < p; j++) scanf("%d", &B[i][j]);
int **C = multiply(A, B, m, n, p);
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) printf("%d ", C[i][j]);
printf("\n");
}
release(A, m); release(B, n); release(C, m);
return 0;
}Example: [1324][5768]=[19432250]. Time O(mnp); extra space O(mp) for the result.
Add two n × n matrices
Write a program to add two n×n matrices and return the resultant matrix.
Element by element
The function
#include <stdio.h>
#include <stdlib.h>
int **add(int **A, int **B, int n) {
int **C = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
C[i] = (int *)malloc(n * sizeof(int));
for (int j = 0; j < n; j++)
C[i][j] = A[i][j] + B[i][j];
}
return C; /* the caller frees C */
}Two nested loops of n each: Θ(n2) time and Θ(n2) space for C.
Booklet answer · Add two n × n matrices
#include <stdio.h>
#include <stdlib.h>
int **readMatrix(int n) {
int **M = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
M[i] = (int *)malloc(n * sizeof(int));
for (int j = 0; j < n; j++) scanf("%d", &M[i][j]);
}
return M;
}
#include <stdio.h>
#include <stdlib.h>
int **add(int **A, int **B, int n) {
int **C = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
C[i] = (int *)malloc(n * sizeof(int));
for (int j = 0; j < n; j++)
C[i][j] = A[i][j] + B[i][j];
}
return C; /* the caller frees C */
}
int main(void) {
int n;
scanf("%d", &n);
int **A = readMatrix(n), **B = readMatrix(n);
int **C = add(A, B, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) printf("%d ", C[i][j]);
printf("\n");
}
for (int i = 0; i < n; i++) { free(A[i]); free(B[i]); free(C[i]); }
free(A); free(B); free(C);
return 0;
}Example: [1324]+[5768]=[610812]. Time Θ(n2).
See matrix multiplication move
Structures
struct employee {
int id;
char name[30];
float salary;
};
struct employee e = {1, "Asha", 52000.0f};
struct employee *p = &e;
e.salary = 55000; /* dot: through the variable */
p->salary = 56000; /* arrow: through a pointer, = (*p).salary */Opens chatgpt.com in a new tab with a ready-made prompt for this topic.
Primitive data types versus structures
Define and explain the differences between primitive data types and structures in programming. Provide an example in C demonstrating the declaration and usage of both.
Definitions and the differences
Example program
#include <stdio.h>
#include <string.h>
struct book { /* user-defined: groups different types */
int id;
char title[40];
float price;
};
int main(void) {
int count = 3; /* primitive: one value of one built-in type */
float rate = 4.5f;
char grade = 'A';
struct book b;
b.id = 101;
strcpy(b.title, "Data Structures");
b.price = 499.0f;
printf("%d %.1f %c\n", count, rate, grade);
printf("%d %s %.2f\n", b.id, b.title, b.price);
printf("sizeof(int) = %zu, sizeof(struct book) = %zu\n", sizeof(int), sizeof(struct book));
return 0;
}Booklet answer · Primitive data types versus structures
A primitive data type is a built-in type that holds one value (int, float, char, double). A structure is a user-defined type, declared with struct, that groups related members of possibly different types into one unit.
Differences: primitives are predefined, hold a single value of a fixed size, and support arithmetic directly. Structures are defined by the programmer, hold many values of mixed types, have a size equal to the sum of the members plus padding, are accessed member by member with . or ->, and cannot be added or compared with ==.
#include <stdio.h>
#include <string.h>
struct book { /* user-defined: groups different types */
int id;
char title[40];
float price;
};
int main(void) {
int count = 3; /* primitive: one value of one built-in type */
float rate = 4.5f;
char grade = 'A';
struct book b;
b.id = 101;
strcpy(b.title, "Data Structures");
b.price = 499.0f;
printf("%d %.1f %c\n", count, rate, grade);
printf("%d %s %.2f\n", b.id, b.title, b.price);
printf("sizeof(int) = %zu, sizeof(struct book) = %zu\n", sizeof(int), sizeof(struct book));
return 0;
}Student or employee records with structures and pointers
Write a C program to store students information using structures. How effectively improved using pointers?
Write a C program to store information of employees using user defined structures and pointers.
The plan
Define the record as a structure, allocate an array of n records with malloc, read and print them through a pointer with the -> operator, then free the memory.
For employees, rename the members: id, name, designation, salary. The program is otherwise the same.
The program
#include <stdio.h>
#include <stdlib.h>
struct student {
int roll;
char name[30];
float marks;
};
int main(void) {
int n;
printf("Number of students: ");
scanf("%d", &n);
/* one block of exactly n records, reached through a pointer */
struct student *s = (struct student *)malloc(n * sizeof(struct student));
if (s == NULL) return 1;
for (int i = 0; i < n; i++) {
printf("Roll, name, marks: ");
scanf("%d %29s %f", &(s + i)->roll, (s + i)->name, &(s + i)->marks);
}
printf("\nRoll Name Marks\n");
for (struct student *p = s; p < s + n; p++) /* pointer walks the array */
printf("%-5d %-15s %6.2f\n", p->roll, p->name, p->marks);
free(s);
return 0;
}How pointers improve it
malloc(n * sizeof(struct student)) allocates exactly n records at run time instead of a fixed struct student s[100].Booklet answer · Student or employee records with structures and pointers
#include <stdio.h>
#include <stdlib.h>
struct student {
int roll;
char name[30];
float marks;
};
int main(void) {
int n;
printf("Number of students: ");
scanf("%d", &n);
/* one block of exactly n records, reached through a pointer */
struct student *s = (struct student *)malloc(n * sizeof(struct student));
if (s == NULL) return 1;
for (int i = 0; i < n; i++) {
printf("Roll, name, marks: ");
scanf("%d %29s %f", &(s + i)->roll, (s + i)->name, &(s + i)->marks);
}
printf("\nRoll Name Marks\n");
for (struct student *p = s; p < s + n; p++) /* pointer walks the array */
printf("%-5d %-15s %6.2f\n", p->roll, p->name, p->marks);
free(s);
return 0;
}Improvement with pointers: malloc gives exactly n records, so no memory is wasted and there is no fixed limit. Functions receive a pointer (a few bytes) instead of a copy of the whole structure, and can update the original record. A pointer steps through the records with p++. Pointer members also let records be linked into dynamic structures such as linked lists. (For employees, use the members id, name, designation and salary in the same program.)
Result processing of students (pseudocode)
Write pseudo code to perform result processing of a student. The student structure contains the following fields: (i) name (ii) no (iii) Mark1, Mark2, Mark3.
Decide what “result processing” produces
For each student compute the total, the average, and PASS or FAIL. The pass mark is not given, so state the assumption: a student passes with at least 50 in every subject.
Add total, average and result as extra fields of the structure, so the output can be printed as a table at the end.
Trace for two students
| No | Name | Marks | Total | Average | Result |
|---|---|---|---|---|---|
| 1 | Ravi | 78, 65, 90 | 233 | 77.67 | PASS |
| 2 | Meena | 45, 80, 70 | 195 | 65.00 | FAIL (45 < 50) |
Booklet answer · Result processing of students (pseudocode)
STRUCT Student
name, no
mark1, mark2, mark3
total, average, result
ALGORITHM ProcessResults(S[1..n])
1. FOR i <- 1 TO n DO
2. READ S[i].name, S[i].no, S[i].mark1, S[i].mark2, S[i].mark3
3. S[i].total <- S[i].mark1 + S[i].mark2 + S[i].mark3
4. S[i].average <- S[i].total / 3
5. IF S[i].mark1 >= 50 AND S[i].mark2 >= 50 AND S[i].mark3 >= 50 THEN
6. S[i].result <- "PASS"
7. ELSE
8. S[i].result <- "FAIL"
9. END FOR
10. PRINT "No Name Total Average Result"
11. FOR i <- 1 TO n DO
12. PRINT S[i].no, S[i].name, S[i].total, S[i].average, S[i].result
13. END FORExample: Ravi (78, 65, 90) gets total 233, average 77.67, PASS. Meena (45, 80, 70) gets total 195, average 65.00, FAIL because Mark1 is below 50.
Passing structures to functions
Explain passing structures to a function with suitable examples for the following: (i) Passing individual members (ii) Passing entire structure.
The two ways
(i) Individual members: pass a.x, a.y as ordinary arguments. The function sees plain variables and does not need to know the structure exists.
Example
#include <stdio.h>
struct point { int x, y; };
/* (i) individual members: each member is copied like an ordinary variable */
int sumXY(int x, int y) { return x + y; }
/* (ii) the entire structure by value: the function gets a full copy */
void show(struct point p) {
p.x = 100; /* changes only the copy */
printf("(%d, %d)\n", p.x, p.y);
}
/* (iii) bonus: by address, so the function can change the caller's structure */
void moveRight(struct point *p) { p->x += 1; }
int main(void) {
struct point a = {3, 4};
printf("%d\n", sumXY(a.x, a.y)); /* prints 7 */
show(a); /* prints (100, 4) */
printf("%d\n", a.x); /* still 3 */
moveRight(&a);
printf("%d\n", a.x); /* now 4 */
return 0;
}Booklet answer · Passing structures to functions
(i) Passing individual members: each member is passed as a separate argument, like any variable of its type, by value. Used when the function needs only one or two fields.
(ii) Passing the entire structure: the structure variable is passed by value; the function receives a copy of all members, so changes are local. Simple, but costly for large structures.
Passing the address (a pointer to the structure) avoids the copy and lets the function change the original.
#include <stdio.h>
struct point { int x, y; };
/* (i) individual members: each member is copied like an ordinary variable */
int sumXY(int x, int y) { return x + y; }
/* (ii) the entire structure by value: the function gets a full copy */
void show(struct point p) {
p.x = 100; /* changes only the copy */
printf("(%d, %d)\n", p.x, p.y);
}
/* (iii) bonus: by address, so the function can change the caller's structure */
void moveRight(struct point *p) { p->x += 1; }
int main(void) {
struct point a = {3, 4};
printf("%d\n", sumXY(a.x, a.y)); /* prints 7 */
show(a); /* prints (100, 4) */
printf("%d\n", a.x); /* still 3 */
moveRight(&a);
printf("%d\n", a.x); /* now 4 */
return 0;
}Inventory management with dynamic memory
Write C functions to implement the inventory management system based on the following specifications by using dynamic memory allocation to manage product records efficiently. Define a structure named Product with fields for product ID, name, quantity, and price. (i) Add a new product to the inventory. (ii) Update the quantity of an existing product. (iii) Calculate and display the total value of the inventory (sum of quantity * price for each product).
Design
Keep the products in a dynamic array Product *inv with a count and a capacity. When it is full, realloc doubles the capacity, so adding is cheap on average and memory grows only as needed.
| Operation | Method | Time |
|---|---|---|
| Add | Grow if full, write at index count | O(1) on average |
| Update quantity | Linear search by id | O(n) |
| Total value | Sum quantity × price | O(n) |
The code and a run
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[30];
int quantity;
float price;
} Product;
Product *inv = NULL; /* dynamic array of products */
int count = 0, capacity = 0;
/* (i) add a product, doubling the block when it is full */
void addProduct(int id, const char *name, int qty, float price) {
if (count == capacity) {
int newCap = capacity ? 2 * capacity : 4;
Product *t = (Product *)realloc(inv, newCap * sizeof(Product));
if (t == NULL) { printf("Out of memory\n"); return; }
inv = t;
capacity = newCap;
}
inv[count].id = id;
strncpy(inv[count].name, name, 29);
inv[count].name[29] = '\0';
inv[count].quantity = qty;
inv[count].price = price;
count++;
}
/* (ii) update the quantity of an existing product */
int updateQuantity(int id, int newQty) {
for (int i = 0; i < count; i++)
if (inv[i].id == id) { inv[i].quantity = newQty; return 1; }
printf("Product %d not found\n", id);
return 0;
}
/* (iii) total value = sum of quantity x price */
float totalValue(void) {
float total = 0;
for (int i = 0; i < count; i++)
total += inv[i].quantity * inv[i].price;
printf("Total inventory value = %.2f\n", total);
return total;
}
int main(void) {
addProduct(101, "Pen", 50, 10.0f);
addProduct(102, "Notebook", 20, 45.5f);
totalValue(); /* 1410.00 */
updateQuantity(101, 80);
totalValue(); /* 1710.00 */
free(inv);
return 0;
}Run: 50×10+20×45.5=500+910=1410. After the update: 80×10+910=1710.
Booklet answer · Inventory management with dynamic memory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[30];
int quantity;
float price;
} Product;
Product *inv = NULL; /* dynamic array of products */
int count = 0, capacity = 0;
/* (i) add a product, doubling the block when it is full */
void addProduct(int id, const char *name, int qty, float price) {
if (count == capacity) {
int newCap = capacity ? 2 * capacity : 4;
Product *t = (Product *)realloc(inv, newCap * sizeof(Product));
if (t == NULL) { printf("Out of memory\n"); return; }
inv = t;
capacity = newCap;
}
inv[count].id = id;
strncpy(inv[count].name, name, 29);
inv[count].name[29] = '\0';
inv[count].quantity = qty;
inv[count].price = price;
count++;
}
/* (ii) update the quantity of an existing product */
int updateQuantity(int id, int newQty) {
for (int i = 0; i < count; i++)
if (inv[i].id == id) { inv[i].quantity = newQty; return 1; }
printf("Product %d not found\n", id);
return 0;
}
/* (iii) total value = sum of quantity x price */
float totalValue(void) {
float total = 0;
for (int i = 0; i < count; i++)
total += inv[i].quantity * inv[i].price;
printf("Total inventory value = %.2f\n", total);
return total;
}
int main(void) {
addProduct(101, "Pen", 50, 10.0f);
addProduct(102, "Notebook", 20, 45.5f);
totalValue(); /* 1410.00 */
updateQuantity(101, 80);
totalValue(); /* 1710.00 */
free(inv);
return 0;
}Sample run: Pen (50 × 10) and Notebook (20 × 45.50) give a total of 1410.00; after updating Pen to 80 the total is 1710.00. Memory is freed at the end.
Self-referential structures
struct node {
int data;
struct node *next; /* correct: a POINTER to the same type */
};It must be a pointer. struct node next; would put a whole node inside a node, inside a node, forever, so the size could never be computed. A pointer has a fixed size (4 or 8 bytes).
Opens chatgpt.com in a new tab with a ready-made prompt for this topic.
Self-referential structures and a basic linked list
Discuss the concept of self-referential structures in the C programming language. How are they typically used in the implementation of dynamic data structures like linked lists? Illustrate with an example, including code snippets, to demonstrate how a self-referential structure can be used to implement a basic linked list.
How the links form a list
Each node is created with malloc when needed. Its next member stores the address of the following node, and the last node stores NULL. A pointer called head remembers the first node.
The code
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next; /* pointer to another node of the same type */
};
struct node *head = NULL;
void insertEnd(int x) {
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = x;
n->next = NULL;
if (head == NULL) { head = n; return; }
struct node *t = head;
while (t->next != NULL) t = t->next;
t->next = n;
}
void display(void) {
for (struct node *t = head; t != NULL; t = t->next)
printf("%d -> ", t->data);
printf("NULL\n");
}
int main(void) {
insertEnd(10);
insertEnd(20);
insertEnd(30);
display(); /* 10 -> 20 -> 30 -> NULL */
return 0;
}Booklet answer · Self-referential structures and a basic linked list
A self-referential structure contains a pointer to a structure of its own type. The pointer (not an embedded copy) keeps the size finite. Linked lists, trees and graphs are built from such nodes: each node is allocated dynamically and its pointer member links it to the next node, ending in NULL.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next; /* pointer to another node of the same type */
};
struct node *head = NULL;
void insertEnd(int x) {
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = x;
n->next = NULL;
if (head == NULL) { head = n; return; }
struct node *t = head;
while (t->next != NULL) t = t->next;
t->next = n;
}
void display(void) {
for (struct node *t = head; t != NULL; t = t->next)
printf("%d -> ", t->data);
printf("NULL\n");
}
int main(void) {
insertEnd(10);
insertEnd(20);
insertEnd(30);
display(); /* 10 -> 20 -> 30 -> NULL */
return 0;
}Uses: linked lists (next), doubly linked lists (prev and next), binary trees (left and right), adjacency lists of graphs.
University student records: design, operations and complexity
A university manages thousands of student records with frequent insertions, deletions, and searches by ID and GPA. Memory efficiency and fast query performance are critical. (a) Design a dynamic structure using pointers and self-referential structures. (b) Implement insert, delete, and search operations. (c) Analyze time-space complexity using Big O, Omega, and Theta. (d) Compare with array-based implementation.
(a) The design
Each record is a self-referential node holding id, name, GPA and a next pointer. The list is kept sorted by id, so a search by id can stop as soon as it passes the wanted id.
(b) Insert, delete and search
struct student {
int id;
char name[30];
float gpa;
struct student *next; /* self-referential link */
};
struct student *head = NULL; /* list kept sorted by id */
/* insert in id order: O(n) to find the place, O(1) to link */
void insert(int id, const char *name, float gpa) {
struct student *n = malloc(sizeof *n);
n->id = id; strcpy(n->name, name); n->gpa = gpa;
if (head == NULL || id < head->id) { n->next = head; head = n; return; }
struct student *t = head;
while (t->next != NULL && t->next->id < id) t = t->next;
n->next = t->next;
t->next = n;
}
/* search by id: stop early because the list is sorted */
struct student *searchId(int id) {
for (struct student *t = head; t != NULL && t->id <= id; t = t->next)
if (t->id == id) return t;
return NULL;
}
/* search by GPA: every record must be checked */
void searchGpa(float lo, float hi) {
for (struct student *t = head; t != NULL; t = t->next)
if (t->gpa >= lo && t->gpa <= hi) printf("%d %s %.2f\n", t->id, t->name, t->gpa);
}
/* delete by id: unlink, then free the node */
int delete(int id) {
struct student *t = head, *prev = NULL;
while (t != NULL && t->id != id) { prev = t; t = t->next; }
if (t == NULL) return 0; /* not found */
if (prev == NULL) head = t->next; /* deleting the first node */
else prev->next = t->next;
free(t);
return 1;
}(c) Complexity
| Operation | Best case Ω | Worst case O | Average Θ |
|---|---|---|---|
| Insert (sorted) | Ω(1): goes before the head | O(n): goes at the end | Θ(n) |
| Delete by id | Ω(1): the head | O(n) | Θ(n) |
| Search by id | Ω(1) | O(n) | Θ(n) |
| Search by GPA range | Θ(n): every node is checked | Θ(n) | Θ(n) |
Space: Θ(n) for n records, plus one pointer (8 bytes) per node. No unused capacity is ever reserved.
(d) Compared with an array
| Point | Sorted array | Sorted linked list |
|---|---|---|
| Search by id | O(log n) with binary search | O(n): no random access |
| Insert / delete | O(n): elements must shift | O(1) once the place is found; no shifting |
| Size | Fixed, or costly to resize | Grows and shrinks node by node |
| Memory | Unused capacity is wasted | Exact, plus one pointer per node |
| Cache behaviour | Good: contiguous | Poorer: nodes scattered |
Booklet answer · University student records: design, operations and complexity
(a) Design: a sorted singly linked list of self-referential nodes struct student { int id; char name[30]; float gpa; struct student *next; }, ordered by id, allocated and freed one record at a time.
(b) Operations:
struct student {
int id;
char name[30];
float gpa;
struct student *next; /* self-referential link */
};
struct student *head = NULL; /* list kept sorted by id */
/* insert in id order: O(n) to find the place, O(1) to link */
void insert(int id, const char *name, float gpa) {
struct student *n = malloc(sizeof *n);
n->id = id; strcpy(n->name, name); n->gpa = gpa;
if (head == NULL || id < head->id) { n->next = head; head = n; return; }
struct student *t = head;
while (t->next != NULL && t->next->id < id) t = t->next;
n->next = t->next;
t->next = n;
}
/* search by id: stop early because the list is sorted */
struct student *searchId(int id) {
for (struct student *t = head; t != NULL && t->id <= id; t = t->next)
if (t->id == id) return t;
return NULL;
}
/* search by GPA: every record must be checked */
void searchGpa(float lo, float hi) {
for (struct student *t = head; t != NULL; t = t->next)
if (t->gpa >= lo && t->gpa <= hi) printf("%d %s %.2f\n", t->id, t->name, t->gpa);
}
/* delete by id: unlink, then free the node */
int delete(int id) {
struct student *t = head, *prev = NULL;
while (t != NULL && t->id != id) { prev = t; t = t->next; }
if (t == NULL) return 0; /* not found */
if (prev == NULL) head = t->next; /* deleting the first node */
else prev->next = t->next;
free(t);
return 1;
}(c) Complexity: insert, delete and search by id are Ω(1) best (at the head), O(n) worst, Θ(n) average; search by GPA is Θ(n). Space is Θ(n) with one extra pointer per record. For faster queries the same node with left and right pointers forms a BST on id, and an AVL tree guarantees O(log n) for all three operations.
(d) Versus array: a sorted array searches in O(log n) but inserts and deletes in O(n) because of shifting and has a fixed capacity; the linked list never shifts, uses exactly the memory needed, but searches sequentially.
Measuring an algorithm
We care about how the count grows for large n, so constants and smaller terms are dropped: 7nlogn+3n+20 grows like nlogn.
Opens chatgpt.com in a new tab with a ready-made prompt for this topic.
The three notations
Asymptotic notations: definitions, graphs, examples
How mathematical notations are used to measure the complexity of an algorithm? Explain different notations.
Illustrate briefly on Big oh Notation, Omega Notation and Theta Notations. Depict the same graphically and explain.
Discuss the importance of mathematical notations in analyzing algorithms. Explain asymptotic notations Big O, Omega, and Theta with examples, and describe how they are used to express the efficiency of algorithms.
Why notations are needed
- Actual running time depends on the machine, compiler and language. Counting steps as a function of n removes those factors.
- Only the growth for large n matters, so a notation that ignores constants lets two algorithms be compared fairly.
- The notations state guarantees: an upper limit (worst case), a lower limit (best case), or the exact rate.
Big-O with a worked example
Show f(n)=3n+2=O(n): for n≥2, 3n+2≤3n+n=4n. So c=4, n0=2.
Omega and Theta with examples
3n+2≥3n for all n≥1, so 3n+2=Ω(n) with c=3, n0=1.
Expressing efficiency: the growth ladder
| Class | Example | n = 1000, steps about |
|---|---|---|
| O(1) | Array access a[i] | 1 |
| O(log n) | Binary search | 10 |
| O(n) | Linear search | 1,000 |
| O(n log n) | Merge sort | 10,000 |
| O(n²) | Bubble sort, two nested loops | 1,000,000 |
| O(2ⁿ) | All subsets | more than 10³⁰⁰ |
Booklet answer · Asymptotic notations: definitions, graphs, examples
Importance: asymptotic notations describe how the running time or space of an algorithm grows with the input size n, independent of machine and language, ignoring constants and lower-order terms. They give an upper limit, a lower limit or the exact growth rate, which lets algorithms be compared.
Big-O: f(n)=O(g(n)) iff ∃c>0,n0 such that f(n)≤cg(n) ∀n≥n0. Upper bound, worst case. Example: 3n+2≤4n for n≥2, so 3n+2=O(n).
Big-Omega: f(n)=Ω(g(n)) iff f(n)≥cg(n) ∀n≥n0. Lower bound, best case. Example: 3n+2≥3n, so Ω(n).
Big-Theta: f(n)=Θ(g(n)) iff c1g(n)≤f(n)≤c2g(n) ∀n≥n0. Tight bound. Example: 3n≤3n+2≤4n for n≥2, so Θ(n).
Use: linear search is O(n) worst, Ω(1) best; binary search O(log n); bubble sort O(n²); merge sort Θ(n log n). Order of growth: 1 < log n < n < n log n < n² < n³ < 2ⁿ < n!.
Tight bound of a cubic, and a proof that something is not O(n²)
(a) Find the tight bound of running time of a cubic function. f(n) = 2n³ + 3n + 6; g(n) = n³. (b) Prove that 10n³ + 20n is not O(n²).
(a) Lower bound
Since 3n+6>0, 2n3+3n+6≥2n3 for all n≥1. So c1=2.
(a) Upper bound
For n≥1, n≤n3 and 1≤n3, so
(b) Proof by contradiction
Suppose 10n3+20n=O(n2). Then there are c,n0 with 10n3+20n≤cn2 for all n≥n0. Divide by n2:
Booklet answer · Tight bound of a cubic, and a proof that something is not O(n²)
(a) For n≥1: 2n3≤2n3+3n+6≤2n3+3n3+6n3=11n3. Hence c1g(n)≤f(n)≤c2g(n) with c1=2, c2=11, n0=1, so f(n)=Θ(n3): the tight bound is n3.
(b) Assume 10n3+20n≤cn2 for all n≥n0. Dividing by n2 gives 10n+20/n≤c, so n≤c/10 for all n≥n0, which is false for n>max(n0,c/10). Contradiction; therefore 10n3+20n=O(n2).
Tabular method: a triple loop
Calculate the time complexity for the following code using Tabular method. Specify the asymptotic time complexity (worst case) for the given algorithm.
void calculate(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
for (int k = 0; k < 10; k++) {
sum += arr[j];
}
}
}
printf("%d\n", sum);
}How many times each loop runs
For a fixed i, j runs from i to n − 1: that is n−i iterations. Over all i:
The table
| Statement | Steps per execution | Frequency | Total |
|---|---|---|---|
| int sum = 0 | 1 | 1 | 1 |
| for i (test) | 1 | n + 1 | n+1 |
| for j (test) | 1 | ∑(n−i+1) | 2n(n+1)+n |
| for k (test) | 1 | 11 per (i, j) | 211n(n+1) |
| sum += arr[j] | 1 | 10 per (i, j) | 5n(n+1) |
| printf | 1 | 1 | 1 |
Booklet answer · Tabular method: a triple loop
| Statement | s/e | Frequency | Total |
|---|---|---|---|
| int sum = 0 | 1 | 1 | 1 |
| for i | 1 | n + 1 | n + 1 |
| for j | 1 | n(n+1)/2 + n | n(n+1)/2 + n |
| for k | 1 | 11 · n(n+1)/2 | 11n(n+1)/2 |
| sum += arr[j] | 1 | 10 · n(n+1)/2 | 5n(n+1) |
| printf | 1 | 1 | 1 |
T(n)=11n2+13n+3. Dropping constants and lower terms, the worst-case time complexity is O(n2). Space is O(1) (sum, i, j, k).
Time and space of a nested while loop
Describe the concept of time and space complexity analysis. Analyze the time and space complexity of the given algorithm:
i = 1; sum = 0;
while (i <= n) {
j = 1;
while (j <= n) {
sum = sum + i;
j = j + 1;
}
i = i + 1;
}Count every statement
| Statement | Frequency |
|---|---|
| i = 1; sum = 0 | 2 |
| while (i <= n) | n + 1 |
| j = 1 | n |
| while (j <= n) | n(n + 1) |
| sum = sum + i | n2 |
| j = j + 1 | n2 |
| i = i + 1 | n |
Add up
Space: only i, j, sum and n, whatever the value of n. So the space complexity is O(1).
Booklet answer · Time and space of a nested while loop
Time complexity counts the basic operations as a function of the input size n; space complexity measures the memory used (a fixed part for simple variables and code, plus a variable part that grows with n). Both are expressed asymptotically.
Analysis: the outer loop runs n times, and for each the inner loop runs n times. Counting: 2+(n+1)+n+n(n+1)+2n2+n=3n2+4n+3, so T(n)=Θ(n2). Only four scalar variables are used, so S(n)=O(1). (The final value is sum=n⋅2n(n+1).)
Part A quick check
| Papers | Question | Answer | Why |
|---|---|---|---|
| May 2023 Q2; Jul 2023 Q4; May 2024 Q3; Jul 2024 Q1; Jul 2025 Q1 | Elements in an array are accessed ... | (A) Randomly | Adjacent storage lets the address of a[i] be computed directly: base + i × size. |
| Nov 2025 Q1; May 2023 Q3; Jul 2023 Q3 | Which data structure is non-linear? | Graphs / Hierarchical / Tree | Trees and graphs are non-linear; arrays, lists, stacks and strings are linear. |
| Jul 2024 Q5; Jul 2025 Q5 | Example of a linear data structure? | (D) Linked list and queue | Both arrange elements in a sequence. |
| Jul 2023 Q8; Jul 2024 Q4 | A collection of similar type of data items / best description of an array | Array; (B) container of objects of similar types | Arrays are homogeneous. |
| May 2023 Q1 | How do you instantiate an array in C? | (B) int Arr[3]; | C has no new keyword. |
| Dec 2023 Q4 | How do you initialise an array in C? | (C) int arr[3] = {1,2,3}; | Square brackets for the size, braces for the values. |
| Jul 2023 Q1 | A variable that stores the address of another variable | (D) pointer variable | Definition of a pointer. |
| Nov 2025 Q2 | Operator that gives the value at the address stored in a pointer | (A) * | & gives an address, * dereferences. |
| Jun 2025 Q2 | int x = 10; int *p = &x; printf("%d", *p); | (B) 10 | *p is the value of x. |
| Nov 2025 Q4 | Result of ptr++ | (B) Moves ptr to the next memory location | It adds sizeof(*ptr) to the address. |
| Dec 2023 Q2 | An array a can be pointed to by integer pointer p using | (A) p = &a[0] | Assignment (=), not comparison (==). |
| Jun 2025 Q1 | Access a structure member through a pointer | (B) ptr->member | ptr->member is (*ptr).member. |
| Jul 2025 (set 2) Q1 | Which is not a type of pointer in C? | (D) String pointer | NULL, void (generic), wild and dangling pointers exist; a string is just char *. |
| Nov 2025 Q3 | Header file for malloc() and calloc() | (B) stdlib.h | The memory functions are declared there. |
| Jun 2026 Q4 | Return type of malloc() or calloc() | (A) void * | A generic pointer, cast to the needed type. |
| Nov 2024 Q3 | Which function allocates multiple blocks of the same size? | (C) calloc() | calloc(n, size): n blocks, zero-filled. |
| Jul 2025 (set 2) Q3 | Allocate an int array of size 10 | (B) (int*) malloc(10 * sizeof(int)) | malloc takes bytes, so multiply by the element size. |
| Nov 2024 Q2 | int *p; p = (int *)malloc(20); printf("%d", sizeof(p)); on a 32-bit processor | (B) 4 | sizeof(p) is the size of the pointer, not of the block. |
| May 2023 Q4; Jul 2024 Q2; Jul 2025 Q2 | struct student *s; s->c = "hello"; printf("%s", s->c); | (B) Segmentation fault | s is never initialised, so s->c writes through a garbage address. Strictly it is undefined behaviour; the key's answer is a segmentation fault. |
| Dec 2023 Q3; Jul 2025 (set 2) Q2 | Correct self-referential structure | struct node { int data; struct node *link; }; | The pointer member has the type struct node *. |
| Jun 2026 Q1 | Why a pointer to its own type, not the structure itself? | (B) To avoid infinite recursive expansion of the size | A node inside a node inside a node has no finite size. |
| Nov 2024 Q1 | Definitions that let us use functions while hiding the implementation | (A) Abstract Data Types | An ADT gives the what, not the how. |
| May 2024 Q1 | Which case does not exist in complexity theory? | (D) Base case | Best, worst and average cases exist; base case belongs to recursion. |
| Dec 2023 Q1; Nov 2024 Q4 | We can certainly conclude an algorithm's ___ scenario from asymptotic analysis. | (B) Best, average and worst case | Each case has its own function, and asymptotic notation can describe any of them. Some keys print (C) worst case, because O is usually quoted for the worst case. |
| Jul 2023 Q2; Jun 2025 Q4 | Best-case time of linear search | O(1) | The key is the first element. |
| Jul 2025 (set 2) Q4 | O(n) describes | (C) Linear time | Time grows in proportion to n. |
| Jun 2026 Q2 | 7n log n + 3n + 20 is most precisely | (B) O(n log n) and Θ(n log n) | n log n dominates; both bounds hold, so Θ is exact. |
| Jun 2026 Q3 | Dictionary with very frequent searches and rare insertions | (D) Sorted array with binary search | O(log n) search, no pointer overhead, and the O(n) insert cost hardly matters. (B) is wrong: hashing is not O(1) in all cases. |
| Jun 2025 Q3 | True about matrix multiplication | (D) Both b and c | Associative and distributive over addition, but not commutative. |
| May 2024 Q2 | for (i = 1; i <= 50; i++) printf("hello"); prints hello how many times? | (B) 50 | i takes the values 1 to 50. |
| May 2024 Q4 | Loop guaranteed to execute at least once | (C) do while | Its condition is tested after the body. |
| Jul 2024 Q3 | continue cannot be used with | (D) switch | continue applies only to loops. |
Opens chatgpt.com in a new tab with a ready-made prompt for this topic.
Unit 1 in one page
- Array: same type, adjacent memory, random access in O(1). Declare int a[3] = {1, 2, 3}.
- Pointer: & gives the address, * the value; p++ moves by sizeof(*p); ptr->m equals (*ptr).m.
- malloc (one block, garbage), calloc (n blocks, zeros), realloc (resize), free; all in stdlib.h, all return void *.
- 2D dynamic matrix: int **m, malloc r row pointers, then each row; free rows first.
- Structure: groups mixed types; pass members, the whole structure (copy) or its address (no copy).
- Self-referential: a member that is a pointer to its own type; the basis of lists and trees.
- O upper, Ω lower, Θ both; always give c and n₀; drop constants and lower terms.
- Tabular method: frequency of each statement (loop tests run one extra time), add, keep the highest power.
Unit 1 checklist
Before you move on, can you do each of these without looking?
0 of 6 topics complete
Not sure about one? Go back to it in the topic list and press Next step through the worked question once more. Ticks are saved in this browser. Final checklist for the subject →
Unit complete. Up next: Unit 2, Lists.
All units