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
).
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]
const int MAXSIZE = 366; ... int temperature[MAXSIZE]; int numOfTemps = 0; // Number of entries in temperature.
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; }
Very few operations are legal for arrays.