Arrays
Arrays
This domain tests one- and two-dimensional arrays, initialization, traversal and simple algorithms. An array is a fixed-size collection of elements of the same type stored in contiguous memory. Indexing starts at 0, so an array of size n has valid indices 0 to n-1. The array name acts as the base address in most expressions.
Rules
- Declaration:
int a[5];; initialization:int a[5] = {2,4,6,8,10};. If fewer initializers are given, the rest become 0. - Traverse with a loop from 0 to n-1; do not hard-code the size when a constant is available.
- A 2D array
int m[2][3]has 2 rows and 3 columns; nested loops are used, often row-major. - Common operations: sum, average, maximum/minimum, linear search, bubble sort.
Worked example
For int a[5] = {2,4,6,8,10};, find the average. sum = 0; loop i = 0 to 4 adds a[i], giving 30. avg = sum / 5 would give 6 as an integer. To get 6.0, write float avg = (float)sum / 5;. The cast happens before division, so the result is floating point.
Traps
Accessing a[5] for a 5-element array is out of bounds; C++ does not check this. An uninitialized local array has garbage values. int a[] = {1,2,3}; is allowed, but its size is fixed after compilation. Character arrays need a null terminator for C-style strings. Array assignment a = b is invalid.