An array isn’t a “data type” like you’d normally think of one. It is a collection of the same type of data, similar to a List in Python.
Behind the scenes, there are a few things you need to know however:
- In an array, all elements must be of the same data type.
- When constructed, the array must use a contiguous memory space for all elements.
- To access a specific element, you use the name of the array, and it’s index.
Defining an Array
To declare an array, you specify the data type, the array name, and inside of square brackets, the size of the array.
dataType arrayName[sizeOfArray];
An example of this might be:
double quizScores[5];
// or you could use a variable or constant to define the size
// just make sure the variable is an integer
const int NUM_OF_ASSIGNMENTS = 5;
double homeworkScores[NUM_OF_ASSIGNMENTS];
Accessing Array Values
To read or assign a value to an array, you need the array name and the index.
Inside of square bracket put the index of the element you wish to read or write.
int classSize[5];
classSize[0] = 4;
classSize[1] = 12;
classSize[2] = 11;
classSize[3] = 9;
classSize[4] = 10;
cout << "The size of class 3 is: " << classSize[2] << endl;
Notice that the index starts at zero (0) and ends at the size of the array, minus 1 (size – 1).
Much of how you use variables now, you can do with arrays.
counter[3] = counter[2] + counter[1]; // add elements 2 and 3 and store in 4
value[0]++; // increment the value of the first element
Initialize an Array
You can initialize and array when you define it. That way you can apply the values easier. Put the values in the curly braces, and separate the values by commas.
double temps[5] = {40.0,49.2,61,63.7,61.1};
However, when you initialize an array, you don’t have to give a size. C++ can figure it out and fill it in for you. Just put the values in the curly braces.
int myList[] = {32,64,56,72,81,99};
Introduction to Arrays in C++ was originally found on Access 2 Learn