SemSure
←Data Structures & Algorithms · Unit 1Data structures, ADTs, arrays and pointers✓ 0/61/76
① Topic

What a data structure is

Definition · Data structure
A way of storing and organising data in memory so that the operations we need (insert, delete, search, traverse) are efficient.
Definition · Linear and non-linear
In a linear data structure the elements form a sequence, each with one successor: array, linked list, stack, queue. In a non-linear one an element can be connected to several others, giving a hierarchy or a network: tree, graph.
Definition · Abstract Data Type (ADT)
A set of values together with the operations allowed on them, described by what the operations do and not how they are implemented. A stack ADT promises push, pop and top. Whether it is built on an array or a linked list is hidden.
Samjho
ADT matlab “menu card”: kya-kya order kar sakte ho (operations) likha hai, kitchen mein kaise banta hai (implementation) chhupa hai. Data structure woh actual kitchen hai.

Opens chatgpt.com in a new tab with a ready-made prompt for this topic.

③ Learn · step 1 of 2

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:

1 of 4
③ Learn · step 2 of 2

Pointers in one slide

Definition · Pointer
A variable that stores the address of another variable.
1 of 3
① Topic

Dynamic memory allocation

Definition · Dynamic memory allocation
Allocating memory at run time from the heap, in exactly the amount the program needs, and releasing it when done. The functions are declared in stdlib.h.
FunctionWhat it doesExample
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 zeroint *a = calloc(n, sizeof(int));
realloc(p, size)Resizes an existing block, keeping its contentsa = realloc(a, 2 * n * sizeof(int));
free(p)Returns the block to the heapfree(a);
Samjho
Static array = pehle se 100 seats book kar li, chahe 10 log aayein. Dynamic = jitne log aaye utni seats, aur zarurat pade toh realloc se badha lo. Kaam khatam, free karke seats wapas.

Opens chatgpt.com in a new tab with a ready-made prompt for this topic.

② Question

Creating arrays dynamically, and why it helps

8 marksAsked in: May 2024 Q21a; Jul 2025 Q21a

How arrays can be created dynamically? Prove how it improves the performance of a program.

③ Learn · step 1 of 3

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.

③ Learn · step 2 of 3

The program

Dynamic array with malloc, realloc and 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;
}
③ Learn · step 3 of 3

How it improves performance

PointStatic int a[1000]Dynamic malloc(n * sizeof(int))
Memory for n = 104000 bytes40 bytes
Size decidedAt compile timeAt run time
Need more roomImpossiblerealloc grows the block
When doneHeld until the function returnsfree releases it at once
LifetimeEnds with the functionLasts until free, so a function can return it

Access time is the same, per element, in both cases. The gain is memory: the program uses exactly 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.

Common mistake Do not claim that dynamic arrays are faster to index. They are not. The improvement is in memory use and flexibility.
④ Exam answer

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 .

② Question

Dynamic 2D matrices and matrix multiplication

8 marksAsked in: Nov 2025 Q21b

What is dynamic memory allocation? Explain how dynamic memory allocation is applied for input matrices while performing matrix multiplication.

8 marksAsked in: Jun 2025 Q21b

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.

8 marksAsked in: May 2023 Q21a

Define a function to multiply two m x n matrices and return the resultant matrix.

③ Learn · step 1 of 3

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.

1 of 3
③ Learn · step 2 of 3

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

1 of 4
③ Learn · step 3 of 3

The complete program

Matrix multiplication with dynamically allocated matrices
#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 times, so the time is , or for square matrices.

④ Exam answer

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: . Time ; extra space for the result.

② Question

Add two n × n matrices

8 marksAsked in: Jul 2023 Q21a

Write a program to add two n×n matrices and return the resultant matrix.

③ Learn · step 1 of 2

Element by element

1 of 3
③ Learn · step 2 of 2

The function

add() returns a newly allocated n × n matrix
#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: time and space for C.

④ Exam answer

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: . Time .

③ Learn

See matrix multiplication move

Interactive animationMatrix multiplication, cell by cellNew tab ↗
① Topic

Structures

Definition · Structure
A user-defined data type that groups variables of different types under one name. Each variable inside is a member.
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 */
Samjho
Array = ek hi type ke cheezon ki line. Structure = ek bande ki poori file: naam (char), roll (int), marks (float), sab ek saath. Variable ho toh dot, pointer ho toh arrow.

Opens chatgpt.com in a new tab with a ready-made prompt for this topic.

② Question

Primitive data types versus structures

8 marksAsked in: Jun 2025 Q21a

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.

③ Learn · step 1 of 2

Definitions and the differences

Definition · Primitive data type
A basic type built into the language that holds a single value: int, float, double, char.
1 of 3
③ Learn · step 2 of 2

Example program

Primitive variables and a structure side by side
#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;
}
④ Exam answer

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;
}
② Question

Student or employee records with structures and pointers

8 marksAsked in: May 2024 Q21b; Jul 2025 Q21b

Write a C program to store students information using structures. How effectively improved using pointers?

8 marksAsked in: Jul 2024 Q21b

Write a C program to store information of employees using user defined structures and pointers.

③ Learn · step 1 of 3

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.

③ Learn · step 2 of 3

The program

Student records through a structure pointer
#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;
}
③ Learn · step 3 of 3

How pointers improve it

Exact memory: malloc(n * sizeof(struct student)) allocates exactly n records at run time instead of a fixed struct student s[100].
1 of 5
④ Exam answer

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.)

② Question

Result processing of students (pseudocode)

8 marksAsked in: Jul 2023 Q21b

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.

③ Learn · step 1 of 2

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.

③ Learn · step 2 of 2

Trace for two students

NoNameMarksTotalAverageResult
1Ravi78, 65, 9023377.67PASS
2Meena45, 80, 7019565.00FAIL (45 < 50)
④ Exam answer

Booklet answer · Result processing of students (pseudocode)

Pass mark assumed: 50 in each subject
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 FOR

Example: 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.

② Question

Passing structures to functions

8 marksAsked in: Jul 2025 (set 2) Q21a

Explain passing structures to a function with suitable examples for the following: (i) Passing individual members (ii) Passing entire structure.

③ Learn · step 1 of 2

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.

1 of 3
③ Learn · step 2 of 2

Example

All three ways in one program
#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;
}
④ Exam answer

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;
}
② Question

Inventory management with dynamic memory

8 marksAsked in: Jun 2026 Q21a

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).

③ Learn · step 1 of 2

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.

OperationMethodTime
AddGrow if full, write at index countO(1) on average
Update quantityLinear search by idO(n)
Total valueSum quantity × priceO(n)
③ Learn · step 2 of 2

The code and a run

Product inventory
#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: . After the update: .

④ Exam answer

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.

① Topic

Self-referential structures

Definition · Self-referential structure
A structure that has a member which is a pointer to a structure of the same type.
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).

Samjho
Har dabba apne andar agle dabbe ka address rakhta hai, dabba nahi. Isi chain se linked list, tree, graph bante hain.

Opens chatgpt.com in a new tab with a ready-made prompt for this topic.

② Question

Self-referential structures and a basic linked list

8 marksAsked in: Nov 2024 Q21b

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.

③ Learn · step 1 of 2

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.

1 of 3
③ Learn · step 2 of 2

The code

Building and printing a linked list
#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;
}
④ Exam answer

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.

② Question

University student records: design, operations and complexity

15 marks · Part CAsked in: Jun 2026 Q26

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.

③ Learn · step 1 of 4

(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.

1 of 3
③ Learn · step 2 of 4

(b) Insert, delete and search

Sorted singly linked list of student records
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;
}
③ Learn · step 3 of 4

(c) Complexity

OperationBest case ΩWorst case OAverage Θ
Insert (sorted)Ω(1): goes before the headO(n): goes at the endΘ(n)
Delete by idΩ(1): the headO(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.

Exam tip For thousands of records, the same node idea with two pointers (left and right) gives a binary search tree keyed on id, and a balanced one (AVL, Unit 4) makes insert, delete and search . Mention this as the improvement for “fast query performance”.
③ Learn · step 4 of 4

(d) Compared with an array

PointSorted arraySorted linked list
Search by idO(log n) with binary searchO(n): no random access
Insert / deleteO(n): elements must shiftO(1) once the place is found; no shifting
SizeFixed, or costly to resizeGrows and shrinks node by node
MemoryUnused capacity is wastedExact, plus one pointer per node
Cache behaviourGood: contiguousPoorer: nodes scattered
Common mistake Search by GPA is always Θ(n) here, because the list is ordered by id. Say this explicitly; examiners look for it.
④ Exam answer

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.

① Topic

Measuring an algorithm

Definition · Time complexity
The number of basic steps an algorithm performs, as a function of the input size n.
Definition · Space complexity
The extra memory an algorithm needs as a function of n (fixed part for variables and constants, plus a variable part that depends on n).
Definition · Best, worst and average case
The minimum, maximum and expected number of steps over all inputs of size n. Linear search: best case 1 comparison (first element), worst case n, average about n/2.

We care about how the count grows for large n, so constants and smaller terms are dropped: grows like .

Interactive animationCounting stepsNew tab ↗

Opens chatgpt.com in a new tab with a ready-made prompt for this topic.

③ Learn

The three notations

Definition · Big-O (upper bound)
if there are constants and with for all . Used for the worst case.
1 of 4
② Question

Asymptotic notations: definitions, graphs, examples

8 marksAsked in: Nov 2025 Q21a; May 2023 Q21b

How mathematical notations are used to measure the complexity of an algorithm? Explain different notations.

8 marksAsked in: Jul 2025 (set 2) Q21b

Illustrate briefly on Big oh Notation, Omega Notation and Theta Notations. Depict the same graphically and explain.

15 marks · Part CAsked in: Jun 2025 Q26

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.

③ Learn · step 1 of 4

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.
③ Learn · step 2 of 4

Big-O with a worked example

Show : for , . So .

1 of 3
③ Learn · step 3 of 4

Omega and Theta with examples

for all , so with .

1 of 4
③ Learn · step 4 of 4

Expressing efficiency: the growth ladder

ClassExamplen = 1000, steps about
O(1)Array access a[i]1
O(log n)Binary search10
O(n)Linear search1,000
O(n log n)Merge sort10,000
O(n²)Bubble sort, two nested loops1,000,000
O(2ⁿ)All subsetsmore than 10³⁰⁰
Common mistake Every definition needs the words “for all n ≥ n₀” and named constants. Writing only “f grows slower than g” loses marks.
④ Exam answer

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: iff such that . Upper bound, worst case. Example: for , so .

ntimen₀c·g(n)f(n)
f(n) = O(g(n)): after n₀, f(n) stays below c·g(n)

Big-Omega: iff . Lower bound, best case. Example: , so .

ntimen₀c·g(n)f(n)
f(n) = Ω(g(n)): after n₀, f(n) stays above c·g(n)

Big-Theta: iff . Tight bound. Example: for , so .

ntimen₀c₂·g(n)c₁·g(n)f(n)
f(n) = Θ(g(n)): after n₀, f(n) stays between c₁·g(n) and c₂·g(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!.

② Question

Tight bound of a cubic, and a proof that something is not O(n²)

10 marksAsked in: Dec 2023 Q21

(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²).

③ Learn · step 1 of 3

(a) Lower bound

Since , for all . So .

③ Learn · step 2 of 3

(a) Upper bound

For , and , so

1 of 3
③ Learn · step 3 of 3

(b) Proof by contradiction

Suppose . Then there are with for all . Divide by :

1 of 3
④ Exam answer

Booklet answer · Tight bound of a cubic, and a proof that something is not O(n²)

(a) For : . Hence with , so : the tight bound is .

(b) Assume for all . Dividing by gives , so for all , which is false for . Contradiction; therefore .

② Question

Tabular method: a triple loop

8 marksAsked in: Nov 2024 Q21a

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);
}
③ Learn · step 1 of 2

How many times each loop runs

For a fixed i, j runs from i to n − 1: that is iterations. Over all i:

1 of 4
③ Learn · step 2 of 2

The table

StatementSteps per executionFrequencyTotal
int sum = 011
for i (test)1n + 1
for j (test)1
for k (test)111 per (i, j)
sum += arr[j]110 per (i, j)
printf11
1 of 3
④ Exam answer

Booklet answer · Tabular method: a triple loop

Statements/eFrequencyTotal
int sum = 0111
for i1n + 1n + 1
for j1n(n+1)/2 + nn(n+1)/2 + n
for k111 · n(n+1)/211n(n+1)/2
sum += arr[j]110 · n(n+1)/25n(n+1)
printf111

. Dropping constants and lower terms, the worst-case time complexity is . Space is (sum, i, j, k).

② Question

Time and space of a nested while loop

8 marksAsked in: Jun 2026 Q21b

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;
}
③ Learn · step 1 of 2

Count every statement

StatementFrequency
i = 1; sum = 02
while (i <= n)n + 1
j = 1n
while (j <= n)n(n + 1)
sum = sum + i
j = j + 1
i = i + 1n
③ Learn · step 2 of 2

Add up

Space: only i, j, sum and n, whatever the value of n. So the space complexity is .

④ Exam answer

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: , so . Only four scalar variables are used, so . (The final value is .)

③ Learn

See the bounds move

Interactive animationBig-O, the upper boundNew tab ↗
1 of 3
Practice

Part A quick check

PapersQuestionAnswerWhy
May 2023 Q2; Jul 2023 Q4; May 2024 Q3; Jul 2024 Q1; Jul 2025 Q1Elements in an array are accessed ...(A) RandomlyAdjacent storage lets the address of a[i] be computed directly: base + i × size.
Nov 2025 Q1; May 2023 Q3; Jul 2023 Q3Which data structure is non-linear?Graphs / Hierarchical / TreeTrees and graphs are non-linear; arrays, lists, stacks and strings are linear.
Jul 2024 Q5; Jul 2025 Q5Example of a linear data structure?(D) Linked list and queueBoth arrange elements in a sequence.
Jul 2023 Q8; Jul 2024 Q4A collection of similar type of data items / best description of an arrayArray; (B) container of objects of similar typesArrays are homogeneous.
May 2023 Q1How do you instantiate an array in C?(B) int Arr[3];C has no new keyword.
Dec 2023 Q4How 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 Q1A variable that stores the address of another variable(D) pointer variableDefinition of a pointer.
Nov 2025 Q2Operator that gives the value at the address stored in a pointer(A) *& gives an address, * dereferences.
Jun 2025 Q2int x = 10; int *p = &x; printf("%d", *p);(B) 10*p is the value of x.
Nov 2025 Q4Result of ptr++(B) Moves ptr to the next memory locationIt adds sizeof(*ptr) to the address.
Dec 2023 Q2An array a can be pointed to by integer pointer p using(A) p = &a[0]Assignment (=), not comparison (==).
Jun 2025 Q1Access a structure member through a pointer(B) ptr->memberptr->member is (*ptr).member.
Jul 2025 (set 2) Q1Which is not a type of pointer in C?(D) String pointerNULL, void (generic), wild and dangling pointers exist; a string is just char *.
Nov 2025 Q3Header file for malloc() and calloc()(B) stdlib.hThe memory functions are declared there.
Jun 2026 Q4Return type of malloc() or calloc()(A) void *A generic pointer, cast to the needed type.
Nov 2024 Q3Which function allocates multiple blocks of the same size?(C) calloc()calloc(n, size): n blocks, zero-filled.
Jul 2025 (set 2) Q3Allocate an int array of size 10(B) (int*) malloc(10 * sizeof(int))malloc takes bytes, so multiply by the element size.
Nov 2024 Q2int *p; p = (int *)malloc(20); printf("%d", sizeof(p)); on a 32-bit processor(B) 4sizeof(p) is the size of the pointer, not of the block.
May 2023 Q4; Jul 2024 Q2; Jul 2025 Q2struct student *s; s->c = "hello"; printf("%s", s->c);(B) Segmentation faults 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) Q2Correct self-referential structurestruct node { int data; struct node *link; };The pointer member has the type struct node *.
Jun 2026 Q1Why a pointer to its own type, not the structure itself?(B) To avoid infinite recursive expansion of the sizeA node inside a node inside a node has no finite size.
Nov 2024 Q1Definitions that let us use functions while hiding the implementation(A) Abstract Data TypesAn ADT gives the what, not the how.
May 2024 Q1Which case does not exist in complexity theory?(D) Base caseBest, worst and average cases exist; base case belongs to recursion.
Dec 2023 Q1; Nov 2024 Q4We can certainly conclude an algorithm's ___ scenario from asymptotic analysis.(B) Best, average and worst caseEach 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 Q4Best-case time of linear searchO(1)The key is the first element.
Jul 2025 (set 2) Q4O(n) describes(C) Linear timeTime grows in proportion to n.
Jun 2026 Q27n 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 Q3Dictionary with very frequent searches and rare insertions(D) Sorted array with binary searchO(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 Q3True about matrix multiplication(D) Both b and cAssociative and distributive over addition, but not commutative.
May 2024 Q2for (i = 1; i <= 50; i++) printf("hello"); prints hello how many times?(B) 50i takes the values 1 to 50.
May 2024 Q4Loop guaranteed to execute at least once(C) do whileIts condition is tested after the body.
Jul 2024 Q3continue cannot be used with(D) switchcontinue applies only to loops.

Opens chatgpt.com in a new tab with a ready-made prompt for this topic.

③ Learn

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