Top Banner Ad

ACS101 — Unit 3: Advanced Programming Concepts (C)

Table of Contents (36 sections)

ACS101 · Programming Languages · Unit 3

Advanced Programming Concepts (C)

Unit Scope & Exam Weightage: This unit handles programs that work with collections and memory: 1D array — declaration, input, output, traversal, Simple operations — find max, min, sum, average, Strings in C — gets/puts, strlen, strcpy, strcmp, Pointer — concept of address and pointer variable, Structures and File Handling. It carries 28 PYQ clusters worth 181 marks (25 × 7m and 3 × 2m), the heaviest of the three C units. Three clusters are Survival Mode: array passing to a function, matrix multiplication, and bubble-sort comparison. File handling and structures together add nine more 7-mark questions.


Front Page: Importance-Wise Topic Roadmap (2023–26 PYQs)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 1D array — declaration / input / output / traversal + Simple operations — find max, min, sum, average 9 (2024-25 ×6, 2023-24 ×3) 7m × 8 + 2m = 58m Survival Mode Program
2 File Handling Real connect: Arrays store sensor readings, image pixels, and stock prices 8 (2023-24 ×5, 2024-25 ×3) 7m × 7 + 2m = 51m High Yield Program
3 Structures (including self-referential/union attachments) 5 (2025-26 ×3, 2024-25 ×2) 7m × 5 = 35m High Yield
4 Pointer — concept of address and pointer variable (concept only, not deep) 3 (2024-25, 2023-24 ×2) 7m + 2m × 2 = 11m Concept + Program
5 Strings in C — gets/puts, strlen, strcpy, strcmp 2 (2024-25, 2023-24) 7m × 2 = 14m Program
6 Pointers are the foundation of memory management in embedded systems 2 (2024-25, 2023-24) 7m × 2 = 14m Attached Extra DMA
7 Sorting/searching attachments (bubble, selection, binary, linear) 5 (2024-25 ×4, 2023-24) 7m × 4 + 2m = 30m Attached Extra
8 Linked-list attachment (block diagram, importance) 2 (2024-25) 7m + 2m = 9m Attached Extra

2-Hour Last-Night Survival Checklist:

  1. Array passing: a function parameter int a[] receives the base address, so changes inside the function affect the caller. Prototype int largest(int a[], int n); and loop i=0..n-1.
  2. Matrix multiply: use three nested loops i,j,k with c[i][j] += a[i][k]*b[k][j]; transpose by t[j][i] = c[i][j]. Multiplication is valid only when columns of A equal rows of B.
  3. Bubble vs insertion: bubble repeatedly swaps adjacent out-of-order pairs (O(n²), stable); insertion shifts elements into a sorted prefix (O(n²), but O(n) when already sorted). The given data 7,3,8,5,9,2,4,6 sorts to 2,3,4,5,6,7,8,9.
  4. File modes: r read, w write/truncate, a append, r+/w+/a+ read+write. Always test fp != NULL and call fclose(fp).
  5. Structure vs union: struct allocates memory for every member; union overlays all members in the same memory, so its size is the largest member. This one distinction is a full 7-mark answer with an example.

1. 1D Arrays: Declaration, Input, Output, Traversal

Array: a fixed-size, ordered collection of elements of the same data type stored in contiguous memory. Declaration: type name[size];; indices run from 0 to size-1. The expression a[i] is equivalent to *(a+i).

#include <stdio.h>
#define N 10
int main(void) {
    int a[N], i, max, min, sum = 0;
    float avg;
    for (i = 0; i < N; i++) scanf("%d", &a[i]);   /* input */
    max = min = a[0];
    for (i = 0; i < N; i++) {                     /* traversal */
        printf("%d ", a[i]);                      /* output */
        if (a[i] > max) max = a[i];
        if (a[i] < min) min = a[i];
        sum += a[i];
    }
    avg = (float)sum / N;
    printf("\nmax=%d min=%d sum=%d avg=%.2f\n", max, min, sum, avg);
    return 0;
}
Operation Code fragment Complexity
Traverse for(i=0;i<n;i++) ... O(n)
Find max/min compare each element with running extreme O(n)
Sum/average accumulate then divide by n O(n)
Insert at end a[n++] = x; if capacity permits O(1)
Delete at index k shift a[i]=a[i+1] for i=k..n-2, n-- O(n)
Linear search compare until found O(n)

Passing an array to a function: int largest(int a[], int n) is really int largest(int *a, int n). Only the base address is copied, so the function can modify elements. Use a separate n parameter because sizeof(a) inside the function gives pointer size, not array length.

%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart LR
    A["main: int a[10]"] -->|"base address &a[0]"| B["largest(int a[], int n)"]
    B --> C["read a[0]..a[n-1] directly"]
    C --> D["return maximum to main"]

Examiner Tip: For “importance of array”, write: stores many similar values under one name, enables index-based random access in O(1), forms the basis of matrices/strings/lists, and avoids dozens of separate variables. Four points are enough for a 7-marker when illustrated with a 5-element example.


2. Strings in C: gets/puts, strlen, strcpy, strcmp

String: a character array terminated by the null character '\0'. A string of length 5 needs 6 bytes. gets() reads a line including spaces; puts() prints it with a newline. Prefer fgets() in real code because gets() has no bounds check, but answer exam questions with the requested functions.

Function Header Action Example result
strlen(s) string.h number of characters before \0 strlen("CARE")=4
strcpy(d,s) string.h copy including \0 d becomes "CARE"
strcmp(a,b) string.h compare lexicographically <0, 0, or >0
strcat(d,s) string.h append s to d "CA"+"RE"="CARE"
puts(s) stdio.h print string plus newline —

Reverse a string: find n = strlen(s), then swap s[i] with s[n-1-i] for i = 0..n/2-1. For "HELLO" the swaps are H↔O, E↔L, giving "OLLEH".


3. Pointer — Address and Pointer Variable

Pointer: a variable that stores the memory address of another variable. Declaration: int *p;; assignment p = &a;; dereference p reads/writes the value at that address. & is the address-of operator, is the indirection operator.

int a = 12;
int *p = &a;      /* p holds address of a */
*p = 20;          /* a becomes 20 */
printf("%d %d\n", a, *p);   /* 20 20 */
Expression Meaning
a value of a (12 initially)
&a address of a
p value stored in pointer (address of a)
*p value at that address (the value of a)
int **q pointer to pointer; q = &p

A self-referential pointer points to a structure of its own type, enabling linked lists: struct node { int data; struct node *next; };. This is the memory-management idea used in embedded allocators and OS free lists.


4. Structures, Unions and Self-Referential Structures

Structure: a user-defined aggregate of members of possibly different types, each with its own storage. Union: an aggregate whose members share the same memory location; only one member holds a value at a time.

struct employee {
    char name[30];
    char designation[20];
    float salary;
    char department[20];
    char city[20];
};

struct employee e[100];   /* array of structures */
e[0].salary = 25000.0f;
Feature struct union
Memory Sum of members (plus padding) Size of largest member
Members active All simultaneously One at a time
Example use Employee record Value that may be int/float/string, never all

Self-referential structure: a structure containing a pointer to the same structure type. next links one node to the next; a doubly linked node adds struct node *prev;. Without such a pointer, a chain of records cannot be built dynamically.


5. File Handling in C

File: a named collection of data stored on a secondary device. C treats a file as a stream accessed through a FILE * pointer obtained from fopen(). Text mode processes characters; binary mode processes raw bytes.

Mode Meaning Action if file exists Action if absent
r Read text Opens Fails (NULL)
w Write text Truncates to zero Creates
a Append text Adds at end Creates
r+ Read+write Opens, no truncate Fails
w+ Read+write Truncates Creates
a+ Read+append Adds at end Creates
rb, wb, ab Binary equivalents as above as above
Function Purpose
fopen(name, mode) Open and return FILE *; returns NULL on failure
fclose(fp) Flush buffers and release the stream
fprintf(fp, ...) / fscanf(fp, ...) Formatted write/read
fgetc(fp) / fputc(c, fp) Character write/read
fgets(s, n, fp) / fputs(s, fp) Line write/read
feof(fp) True after an attempted read past end of file
rewind(fp) / fseek(fp, off, origin) Reposition file pointer
#include <stdio.h>
int main(void) {
    FILE *fp = fopen("lines.txt", "w");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    fprintf(fp, "First line\nSecond line\nThird line\n");
    fclose(fp);
    return 0;
}

Examiner Tip: Every file-handling program must contain three visible elements: a NULL check after fopen, a loop that reads until feof or until fgets returns NULL, and fclose at the end. Examiners award one mark for each.


6. Attached Topics: Dynamic Memory, Linked List and Sorting

Dynamic allocation: malloc(n*sizeof(int)) allocates uninitialised bytes; calloc(n, sizeof(int)) allocates and zero-initialises; realloc(p, newsize) resizes; free(p) releases. Advantages over static allocation: size decided at run time, memory released when no longer needed, and no fixed compile-time upper bound.

Linked list: a sequence of nodes data | next. Insertion at head: new->next = head; head = new;. Traversal: for(p=head; p!=NULL; p=p->next). A doubly linked list node carries prev as well; a circular list's last node points back to the head. Use a linked list when insertions/deletions are frequent; use an array when random access by index dominates.

Sorting/searching quick reference:

Method Idea Best Average Worst Stable?
Bubble sort swap adjacent inversions repeatedly O(n) O(n²) O(n²) Yes
Selection sort place minimum at position i O(n²) O(n²) O(n²) No
Insertion sort insert into sorted prefix O(n) O(n²) O(n²) Yes
Linear search check each element O(1) O(n) O(n) —
Binary search halve sorted range O(1) O(log n) O(log n) —

7. Solved Exam-Ready Questions (Exact PYQ Wording)

Solved Q1 (2024-25, 7 Marks | Survival Mode)

Q: Write the importance of array. Write a program to find the sum of two numbers using array passing to function.

Solution: Importance from Section 1. Program:

#include <stdio.h>
int sumArray(int a[], int n) {
    int s = 0;
    for (int i = 0; i < n; i++) s += a[i];
    return s;
}
int main(void) {
    int a[2];
    scanf("%d %d", &a[0], &a[1]);
    printf("Sum = %d\n", sumArray(a, 2));
    return 0;
}

sumArray receives the base address of a, so it reads both elements without copying the array.


Solved Q2 (2024-25, 7 Marks | Survival Mode)

Q: Write a Program to find the multiplication of two n×nn \times n matrix.

Solution:

#include <stdio.h>
#define N 3
int main(void) {
    int a[N][N], b[N][N], c[N][N] = {0}, i, j, k;
    for (i=0;i<N;i++) for (j=0;j<N;j++) scanf("%d", &a[i][j]);
    for (i=0;i<N;i++) for (j=0;j<N;j++) scanf("%d", &b[i][j]);
    for (i=0;i<N;i++)
        for (j=0;j<N;j++)
            for (k=0;k<N;k++)
                c[i][j] += a[i][k] * b[k][j];
    for (i=0;i<N;i++) {
        for (j=0;j<N;j++) printf("%d ", c[i][j]);
        printf("\n");
    }
    return 0;
}

Time complexity is O(n³). Element c[i][j] is the dot product of row i of A and column j of B.


Solved Q3 (2024-25, 7 Marks | Survival Mode)

Q: Write a Program to sort the given list of data using bubble sort and compare its time complexity with insertion sort. Data: 7, 3, 8, 5, 9, 2, 4, 6

Solution:

#include <stdio.h>
int main(void) {
    int a[] = {7,3,8,5,9,2,4,6};
    int n = 8, i, j, t;
    for (i = 0; i < n-1; i++)
        for (j = 0; j < n-1-i; j++)
            if (a[j] > a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; }
    for (i = 0; i < n; i++) printf("%d ", a[i]);
    return 0;
}

After sorting: 2 3 4 5 6 7 8 9. Comparison: bubble performs up to n(n-1)/2 comparisons and swaps (O(n²)); insertion also takes O(n²) on average but only O(n) when the input is already sorted, because each new element needs no shifting. Bubble is stable; insertion is stable too.


Solved Q4 (2023-24, 7 Marks)

Q: Write a program in C language to multiply 2 matrices of order n×nn \times n each and print the resultant matrix along with the transpose of the resultant matrix.

Solution: Use Solved Q2's triple loop, then add:

for (i=0;i<N;i++)
    for (j=0;j<N;j++)
        transpose[j][i] = c[i][j];

Print c row-wise and transpose row-wise. The transpose swaps row and column indices, so for a symmetric result c = transpose.


Solved Q5 (2023-24, 7 Marks)

Q: Write a program in C language to implement Selection sort method.

Solution:

#include <stdio.h>
int main(void) {
    int a[] = {64,25,12,22,11}, n=5, i, j, min, t;
    for (i=0;i<n-1;i++) {
        min = i;
        for (j=i+1;j<n;j++) if (a[j] < a[min]) min = j;
        if (min != i) { t=a[i]; a[i]=a[min]; a[min]=t; }
    }
    for (i=0;i<n;i++) printf("%d ", a[i]);   /* 11 12 22 25 64 */
    return 0;
}

Selection sort makes at most n-1 swaps but always O(n²) comparisons.


Solved Q6 (2023-24, 7 Marks)

Q: Write a C program to find the presence of any particular element in an array of n number of elements using Binary search method.

Solution:

#include <stdio.h>
int main(void) {
    int a[] = {10,20,30,40,50,60}, n=6, key, low=0, high=n-1, mid, found=0;
    scanf("%d", &key);
    while (low <= high) {
        mid = low + (high-low)/2;
        if (a[mid] == key) { found = 1; break; }
        else if (a[mid] < key) low = mid+1;
        else high = mid-1;
    }
    printf(found ? "Found at index %d\n" : "Not found\n", mid);
    return 0;
}

Binary search requires a sorted array and halves the search range each step: O(log n). For key=40, mid=2 (30) → low=3; mid=4 (50) → high=3; mid=3 (40) → found.


Solved Q7 (2023-24, 7 Marks)

Q: Write a Program to print the greatest number of an array using the array passing to function concept.

Solution:

#include <stdio.h>
int greatest(int a[], int n) {
    int g = a[0];
    for (int i=1;i<n;i++) if (a[i] > g) g = a[i];
    return g;
}
int main(void) {
    int a[5], i;
    for (i=0;i<5;i++) scanf("%d", &a[i]);
    printf("Greatest = %d\n", greatest(a,5));
    return 0;
}

Initialise the running maximum with a[0], not with 0, so all-negative arrays work.


Solved Q8 (2023-24, 7 Marks)

Q: Define Sorting. Explain the Bubble sort technique and write the Program to implement the bubble sort.

Solution: Sorting arranges data in a defined order (ascending/descending). Bubble sort repeatedly compares adjacent elements and swaps them if they are out of order; after each pass the largest remaining element “bubbles” to the end. Program from Solved Q3. For [5,1,4,2,8], pass 1 gives [1,4,2,5,8]; pass 2 gives [1,2,4,5,8]; pass 3 makes no swap and the algorithm stops early if a swapped flag is used.


Solved Q9 (2025-26, 7 Marks)

Q: Differentiate between structure and union with suitable example.

Solution: Use the Section 4 table plus:

struct S { int i; float f; };   /* sizeof ≈ 8: 4 + 4 */
union U  { int i; float f; };   /* sizeof = 4: largest member */

In struct S, assigning s.i=5; s.f=2.5; preserves both values. In union U, assigning u.f=2.5; overwrites the bits of u.i.


Solved Q10 (2025-26, 7 Marks)

Q: Create a structure in C language for keeping the records of the employees of an organization about their Name, Designation, Salary, Department and City of posting. Write program to enter records of 100 employees and display the names of those with salary more than 20,000.

Solution:

#include <stdio.h>
#define N 100
struct employee {
    char name[30], designation[20], department[20], city[20];
    float salary;
};
int main(void) {
    struct employee e[N];
    int i;
    for (i=0;i<N;i++) {
        printf("Employee %d: ", i+1);
        scanf("%s %s %f %s %s", e[i].name, e[i].designation,
              &e[i].salary, e[i].department, e[i].city);
    }
    printf("\nEmployees with salary > 20000:\n");
    for (i=0;i<N;i++) if (e[i].salary > 20000) printf("%s\n", e[i].name);
    return 0;
}

Each member is accessed with the dot operator; the float member needs & in scanf.


Solved Q11 (2025-26, 7 Marks)

Q: List out various file operations and modes in C. Write a C program to copy the content from one file to another file.

Solution: Operations: create, open, read, write, append, reposition, close. Modes from Section 5.

#include <stdio.h>
int main(void) {
    FILE *src = fopen("source.txt", "r");
    FILE *dst = fopen("dest.txt", "w");
    int ch;
    if (src == NULL || dst == NULL) { printf("Open failed\n"); return 1; }
    while ((ch = fgetc(src)) != EOF) fputc(ch, dst);
    fclose(src); fclose(dst);
    return 0;
}

Reading with fgetc until EOF copies every byte including newlines; w creates or truncates the destination.


Solved Q12 (2024-25, 7 Marks)

Q: What is a structure in C? Give an example of an array of structures.

Solution: Definition from Section 4. Example:

struct student { int roll; char name[20]; float marks; };
struct student s[3] = {{1,"Asha",88.5},{2,"Ravi",91.0},{3,"Neha",79.5}};
printf("%s %.1f\n", s[1].name, s[1].marks);   /* Ravi 91.0 */

An array of structures stores three complete records contiguously; s[i].member selects a field.


Solved Q13 (2024-25, 7 Marks)

Q: Write a C program to read and display contents of a file.

Solution:

#include <stdio.h>
int main(void) {
    FILE *fp = fopen("data.txt", "r");
    char line[256];
    if (fp == NULL) { printf("File not found\n"); return 1; }
    while (fgets(line, sizeof(line), fp) != NULL) printf("%s", line);
    fclose(fp);
    return 0;
}

fgets keeps the trailing newline already present in the file, so printing with printf("%s", line) avoids a double blank line.


Solved Q14 (2024-25, 7 Marks)

Q: Explain self-referential structures and their use in linked list.

Solution: A self-referential structure contains a pointer to its own type:

struct node {
    int data;
    struct node *next;   /* points to another node of same type */
};

Each node stores data plus the address of the next node. Starting from head, traversal p=p->next visits the whole list ending at NULL. This allows runtime growth and O(1) insertion at the head, unlike a fixed array.


Solved Q15 (2023-24, 7 Marks)

Q: Write a program to delete the end of the file using function feof(). Display the file pointer position for detecting end of file.

Solution:

#include <stdio.h>
int main(void) {
    FILE *fp = fopen("data.txt", "r+");
    long pos = 0;
    int ch;
    if (fp == NULL) return 1;
    while (!feof(fp)) {
        ch = fgetc(fp);
        if (!feof(fp)) pos = ftell(fp);   /* last valid position */
    }
    fseek(fp, pos, SEEK_SET);             /* move to end-of-record */
    fputc(EOF, fp);                       /* conceptual truncation marker */
    printf("End position = %ld\n", pos);
    fclose(fp);
    return 0;
}

In standard C, files are truncated by rewriting with "w" or by OS-specific truncate; feof() becomes true only after a read attempt past the last byte, so ftell() before that attempt gives the end position.


Solved Q16 (2024-25, 7 Marks)

Q: Write a C program to reverse a string entered by the user.

Solution:

#include <stdio.h>
#include <string.h>
int main(void) {
    char s[100], t;
    int i, j, n;
    scanf("%s", s);
    n = strlen(s);
    for (i=0, j=n-1; i<j; i++, j--) { t=s[i]; s[i]=s[j]; s[j]=t; }
    printf("%s\n", s);
    return 0;
}

Two-pointer swapping needs only n/2 exchanges and O(1) extra space.


Solved Q17 (2024-25, 7 Marks)

Q: Write a program in C language using union to store name, mobile number, year of birth, fees deposited, total marks in class 12th and print only name and marks of class 12th of those students who have deposited fees less that 5000 and how born after year 2005.

Solution:

#include <stdio.h>
struct student {
    char name[30];
    union {
        char mobile[15];
        int yearOfBirth;
        float fees;
        float marks12;
    } info;
};
int main(void) {
    struct student s[2];
    int i;
    for (i=0;i<2;i++) {
        printf("Name: "); scanf("%s", s[i].name);
        printf("Fees: "); scanf("%f", &s[i].info.fees);
        printf("Marks12: "); scanf("%f", &s[i].info.marks12);
    }
    /* A union overlays fees and marks12, so both cannot coexist; use a struct for records needing both. */
    printf("Filter requires separate storage for fees and marks12.\n");
    return 0;
}

Important examiner point: the stated requirement is logically inconsistent with a pure union because fees and marks share one memory location; assigning one destroys the other. A correct design keeps name in the struct and stores fees/marks as separate struct members, using a union only for genuinely exclusive fields.


Solved Q18 (2023-24, 7 Marks)

Q: Define any 3 functions which are used for file handling in C language. Write a program in C language to count total number vowels in a text file.

Solution: Three functions: fopen() opens a stream, fgetc() reads one character, fclose() closes the stream.

#include <stdio.h>
int isVowel(int c) {
    return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'
        || c=='A'||c=='E'||c=='I'||c=='O'||c=='U';
}
int main(void) {
    FILE *fp = fopen("text.txt", "r");
    int ch, count = 0;
    if (fp == NULL) return 1;
    while ((ch = fgetc(fp)) != EOF) if (isVowel(ch)) count++;
    printf("Vowels = %d\n", count);
    fclose(fp);
    return 0;
}

Solved Q19 (2025-26, 2 Marks)

Q: List various file opening modes.

Solution: r, w, a, r+, w+, a+ and their binary forms rb, wb, ab, r+b, w+b, a+b. r fails if absent; w truncates or creates; a appends or creates.


Solved Q20 (2024-25, 7 Marks)

Q: Explain the use and importance of Linked list in Programming.

Solution: A linked list stores elements in nodes connected by pointers, not in contiguous memory. Importance: dynamic size, O(1) insertion/deletion at a known position, no memory wastage from a fixed upper bound, and the basis for stacks, queues, graphs' adjacency lists and OS memory free lists. Limitation: O(n) access by index and extra pointer storage per node.


Solved Q21 (2024-25, 7 Marks)

Q: Define Pointer. Discuss the self referential pointer with example.

Solution: Definition from Section 3. A self-referential pointer holds the address of a structure of the same type:

struct node { int data; struct node *next; };
struct node a = {10, NULL}, b = {20, NULL};
a.next = &b;      /* a -> b -> NULL */

Following a.next reaches b; this chain is a linked list. It is used in embedded memory allocators and any structure whose size is unknown at compile time.


Solved Q22 (2023-24, 7 Marks)

Q: What are the advantages of Dynamic memory allocation over static memory allocation? Write a program to display two numbers with malloc () and reallocate memory for displaying three numbers.

Solution: Advantages: size decided at run time, memory can be freed, no fixed compile-time limit, and efficient use for variable-length data.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *p, i;
    p = malloc(2 * sizeof(int));
    if (p == NULL) return 1;
    p[0] = 10; p[1] = 20;
    p = realloc(p, 3 * sizeof(int));
    if (p == NULL) return 1;
    p[2] = 30;
    for (i=0;i<3;i++) printf("%d ", p[i]);   /* 10 20 30 */
    free(p);
    return 0;
}

realloc preserves the old contents and may move the block to a new address; the returned pointer must be used.


Solved Q23 (2023-24, 2 Marks)

Q: Define Pointer to Pointer.

Solution: A pointer to pointer stores the address of another pointer. Declaration: int **q; with q = &p where p is int *. Dereferencing once (*q) gives the value of p (an address); twice (**q) gives the original int.


Solved Q24 (2023-24, 2 Marks)

Q: Draw block diagram to represent doubly linked list.

Solution:

NULL ← prev [10] next ⇄ prev [20] next ⇄ prev [30] next → NULL
        head

Each node has three fields: prev pointer, data, next pointer. The first node's prev is NULL and the last node's next is NULL, enabling traversal in both directions.


Solved Q25 (2024-25, 7 Marks)

Q: Write a C program to input 10 integers in an array and find the average.

Solution:

#include <stdio.h>
int main(void) {
    int a[10], i, sum = 0;
    for (i=0;i<10;i++) { scanf("%d", &a[i]); sum += a[i]; }
    printf("Average = %.2f\n", (float)sum/10);
    return 0;
}

Cast before division: (float)sum/10 gives a fractional average; sum/10 would truncate.


Solved Q26 (2024-25, 7 Marks)

Q: Write a C program to find largest number from four given numbers.

Solution:

#include <stdio.h>
int main(void) {
    int a[4], i, large;
    for (i=0;i<4;i++) scanf("%d", &a[i]);
    large = a[0];
    for (i=1;i<4;i++) if (a[i] > large) large = a[i];
    printf("Largest = %d\n", large);
    return 0;
}

Solved Q27 (2024-25, 7 Marks)

Q: Discuss the use of searching and write the program to find the number in an array using linear search.

Solution: Searching locates a target in a collection; linear search checks elements in order and works on unsorted data.

#include <stdio.h>
int main(void) {
    int a[5] = {4,9,2,7,5}, key, i, pos = -1;
    scanf("%d", &key);
    for (i=0;i<5;i++) if (a[i] == key) { pos = i; break; }
    if (pos >= 0) printf("Found at %d\n", pos);
    else printf("Not found\n");
    return 0;
}

Time: O(n) worst case, O(1) best case when the first element matches.


8. Practice Questions (Self-Test)

  1. (2 Marks) What does strlen("HELLO") return and why does the array need 6 bytes?
  2. (7 Marks) Write a function void reverse(char s[]) using strlen and swapping, then call it from main.
  3. (7 Marks) Write a program to read 5 integers with malloc, find the maximum, and free the memory.
  4. (7 Marks) Write a program to append one text file to another using fopen(..., "a") and fgetc.
  5. (7 Marks) Trace selection sort on [29,10,14,37,13,25] and list the array after each pass.