Arrays
Say your program needs four prices. You could make four variables, price1 to price4. But with a hundred prices, that does not work anymore. An array is one variable that holds many values of the same type, one after the other. You reach each value by its number.
#include <iostream>
using namespace std;
int main() {
int prices[4] = {12, 8, 30, 5};
cout << prices[0] << "\n";
cout << prices[3] << "\n";
return 0;
}
Output:
12
5
int prices[4] makes an array of 4 int values. The list in curly braces gives them their starting values.
The number in square brackets after the name is the index, the position of a value. Indexes start at 0, not at 1. So the first value is prices[0], and in an array of 4 values the last one is prices[3]. There is no prices[4].
index: 0 1 2 3
+----+----+----+----+
prices: | 12 | 8 | 30 | 5 |
+----+----+----+----+
Arrays and loops
Each value in an array works like a normal variable. You can read it, and you can give it a new value. The index can also be a variable, so a for loop can visit every value:
int prices[4] = {12, 8, 30, 5};
prices[1] = 9;
int total = 0;
for (int i = 0; i < 4; i++) {
total += prices[i];
}
cout << "Total: " << total << "\n";
Output:
Total: 56
prices[1] = 9 changes the second value from 8 to 9. Then the loop runs with i equal to 0, 1, 2 and 3, and adds each value to total: 12 + 9 + 30 + 5 is 56. The same four lines of loop would work for an array of a thousand values.
You can also make an array without starting values and fill it later, for example from input:
int numbers[3];
for (int i = 0; i < 3; i++) {
cin >> numbers[i];
}
cout << numbers[0] + numbers[2] << "\n";
Output:
16
With the input 7 3 9, the loop stores 7 in numbers[0], 3 in numbers[1] and 9 in numbers[2]. The first plus the last is 16.
Two rules to remember
The size is fixed. An array made with 4 places always has 4 places. It cannot grow. The next section, Vectors, shows a list that can grow.
C++ does not check the index. If you write prices[10], the program still compiles and runs. It reads whatever is in the memory after the array, or it crashes. When we tried it, the program printed a strange number that was never in the array, a different one on each run, with no error message at all. This is one of the most common bugs in C++. Always keep your index between 0 and the size minus 1.
In the exercise, read 5 numbers into an array. Then print the first one, the last one and the sum of all five.