C++ Tutorial
C++ Arrays
An array is a fixed list of values of one type. Index from 0. Do not walk off the end.
A list under one name
An array holds several values of the same type in one variable. Four quiz scores do not needscore0, score1, score2, and score3. They belong in one array named scores.
Every slot has an index. The first slot is 0, not 1. The last slot of a four-element array is 3. That off-by-one rule is the source of most array bugs.
Declare and initialize
Write the type, the name, then the length in square brackets. The length is a compile-time constant: a literal or a const int. You cannot ask the user for a size and then use that number as the array length in portable C++17.
Example
#include <iostream>
using namespace std;
int main() {
int scores[4] = {88, 91, 74, 95};
cout << scores[0] << endl;
cout << scores[3] << endl;
return 0;
}The braces list the starting values in order. If you give fewer values than the length, the rest become zero for built-in types. If you write int scores[4]; with no braces, the slots are uninitialized — do not print them until you assign values.
Index from zero
Read a slot with name[index]. Assign to a slot the same way. Changing scores[1] does not copy the array; it overwrites that one integer.
| Index | Value in the example |
|---|---|
| 0 | 88 |
| 1 | 91 |
| 2 | 74 |
| 3 | 95 |
There is no scores[4]. The compiler will often let you write it. The program then reads memory that is not part of the array. Do not do that. Stay in 0 through length - 1.
Loop through the slots
A for loop with an index is the usual way to visit every element. Keep the loop conditioni < length, not i <= length.
Example
#include <iostream>
using namespace std;
int main() {
const int kCount = 5;
double temps[kCount] = {16.0, 18.5, 21.0, 19.5, 17.0};
double total = 0.0;
for (int i = 0; i < kCount; i++) {
total = total + temps[i];
}
cout << "average: " << total / kCount << endl;
temps[2] = 22.0;
cout << "midday: " << temps[2] << endl;
return 0;
}A named constant for the length keeps the array, the loop, and the average in sync. Change kCountin one place and the rest of the file still matches.
Size is known at compile time
The compiler must see the length when it builds the program. That is why a raw array cannot grow. You cannotpush a fifth score onto a four-slot array. You declare a bigger array, or you use a different type.
Example
#include <iostream>
using namespace std;
int main() {
int seats[3] = {12, 8, 15};
int n = sizeof(seats) / sizeof(seats[0]);
cout << "slots: " << n << endl;
for (int i = 0; i < n; i++) {
cout << seats[i] << endl;
}
return 0;
}sizeof(seats) is the whole array in bytes. Divide by the size of one element and you get the count. Prefer a const int you wrote yourself. sizeof is easy to misuse once the array is passed into a function — that story comes with pointers.
Stay inside the array
Walking off the end is undefined behavior. The program might print a leftover number, appear to work, or crash later. g++ will not reliably stop you. Count the slots. Loop with i < n.
When the length is not a compile-time constant, or when you need to add and remove items, usestd::vector. That type shows up in a later chapter. For this chapter, a raw array is enough: one type, a fixed length, index from zero.
Example
#include <iostream>
using namespace std;
int main() {
int scores[6] = {6, 9, 4, 10, 7, 8};
int n = 6;
int total = 0;
for (int i = 0; i < n; i++) {
total += scores[i];
}
cout << "sum: " << total << endl;
cout << "last: " << scores[n - 1] << endl;
return 0;
}Next: group related values of different types with a struct.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.
Statistics
A class mean
The arithmetic mean is the sum divided by the count. Five marks 72, 81, 64, 90, 77 average 76.8. One extreme mark pulls that number; the median would tell a different story.
mean = (Σ xᵢ) / n
Example
#include <iostream>
using namespace std;
int main() {
int marks[] = {72, 81, 64, 90, 77};
int sum = 0;
for (int n : marks) {
sum += n;
}
cout << "mean = " << sum / 5.0 << endl;
return 0;
}Physics
Hottest of five samples
A logger stores temperatures in time order. Finding the maximum is one pass: start with the first reading, replace it whenever a later one is larger. These five values peak at 19.1 °C.
Example
#include <iostream>
using namespace std;
int main() {
double celsius[] = {18.2, 18.5, 19.0, 18.8, 19.1};
double max_t = celsius[0];
for (double t : celsius) {
if (t > max_t) max_t = t;
}
cout << "hottest = " << max_t << " C" << endl;
return 0;
}