BIT8122 / BCT8121 · DATA STRUCTURES · CAT 2
Array operations in C
This corrected example implements exactly two operations, as the task requests: a linear search and calculation of the average mark.
How the sample is interpreted
The array has capacity 10, but the sample initializes only 7 marks. The program therefore processes the 7 supplied values—not the 3 unused array slots.
Values12, 20, 13, 14, 16, 17, 8
Sum100
Average14.29
C program
/*
* BIT8122/BCT8121 Data Structures - CAT 2
* Selected array operations: linear search and average calculation.
* Marks has capacity 10, but only the first 7 elements are initialized.
*/
#include <stdio.h>
#define MAX_MARKS 10
int main(void)
{
int Marks[MAX_MARKS] = {12, 20, 13, 14, 16, 17, 8};
const int count = 7;
int searchValue;
int foundIndex = -1;
int sum = 0;
double average;
for (int i = 0; i < count; i++) {
sum += Marks[i];
}
average = (double)sum / count;
printf("Average mark: %.2f\n", average);
printf("Enter a mark to search for: ");
if (scanf("%d", &searchValue) != 1) {
fprintf(stderr, "Invalid input. Enter an integer mark.\n");
return 1;
}
for (int i = 0; i < count; i++) {
if (Marks[i] == searchValue) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
printf("%d was found at position %d (index %d).\n",
searchValue, foundIndex + 1, foundIndex);
} else {
printf("%d was not found in the marks array.\n", searchValue);
}
return 0;
}
Example run
Average mark: 14.29
Enter a mark to search for: 16
16 was found at position 5 (index 4).
The position is counted from 1 for people; the C array index is counted from 0.
Compile: gcc -std=c11 -Wall -Wextra -pedantic data-structures-cat-2.c -o cat2, then run ./cat2.