Arrays, Strings and Simple Data Handling
What the examiner tests
Declaring and traversing arrays, computing sum/average/largest, searching, and handling strings with library functions.
Core rules
- An array stores elements of the same type in contiguous memory.
int a[5];creates indices 0 to 4; the last valid index is size − 1. - Initialise at declaration:
int a[5] = {2, 4, 6, 8, 10};. Partial initialisation fills the rest with 0. - Traversal pattern:
for (i = 0; i < 5; i++)- use<, not<=. Accumulatesum = sum + a[i], or updatemaxwhena[i] > max. - For a maximum, initialise
maxwitha[0], not with 0, so arrays of negative numbers work. - A string is a
chararray ending with the null character'\0'.char s[6] = "WBBSE";needs 6 cells: 5 letters plus'\0'. string.hfunctions:strlen(counts characters but not'\0'),strcpy(copy),strcat(join),strcmp(returns 0 when equal). Compare strings withstrcmp, never with==.
Worked example
Linear search in a = {4, 9, 2, 7} for key 7:
i = 0: 4 ≠ 7; i = 1: 9 ≠ 7; i = 2: 2 ≠ 7; i = 3: 7 = 7 → found at index 3 after 4 comparisons. If the loop finishes without a match, print “not found”.
Traps
- Accessing
a[5]in an array of size 5 - out of bounds. - Forgetting the
'\0'when counting the space needed for a string. - Using
sizeof(s)instead ofstrlen(s);sizeofincludes the terminator and depends on the declared size. - Using
gets(); preferfgets(), which limits input length. - Expecting
scanf("%s", s)to read a full name containing a space - it stops at whitespace.