C++ Notes: Arrays

Many values, one name

An array stores many values in memory using one name, and individual values are identified by number. Unlike math, arrays must be declared and a fixed amount of memory must be allocated for them.

Individual elements are identified by integer subscripts which are enclosed in square brackets [] following the array variable. xi in mathematics is written as x[i] in C++ and most other programming languages.

Arrays are the basic underlying mechanism for storing multiple values, and many additional ways to store values are built on them, especially in the Standard Template Library (STL). A solid understanding of arrays is essential, even tho you will want to use some of STL library data structures.

In general, you should use arrays only for storing a fixed number of elements, and vectors when storing a variable number of elements. This section is about arrays, so it uses them in all examples, even when there are better choices (esp, vector).

Declaring an array

Array size and element type must be declared. All elements must be the same type, eg, all int or all char. Write the element type name, the name of the array variable, then the size enclosed in square brackets ("[]").
int scores[100];  // 100 ints, scores[0] to scores[99]
char name[40];    // 40 chars, name[0] to name[39]

Subscripts start at zero

Subscript ranges always start at zero. This is unfriendly because it isn't the way that humans normally count, but it's the way that C, C++, Java and many other languages do it.

Length of an array

There is no general way to find the length of an array. You must keep the size (both the maximum, and currently filled size) of the array in variables. For example,
const int MAXSIZE = 366;
int temperature[MAXSIZE];
int numOfTemps = 0;  // Number of entries in temperature.

Arrays are to data what loops are to control flow

Loops and arrays go together. This example sets all array elements to zero.

float height[1000];
. . .
for (int i=0; i<1000; i++) {
    height[i] = 0.0;

Operations on arrays

Very few operations are legal for arrays.