Lesson 5

Arrays

Short answer: an array is a row of boxes of the same type, side by side in memory, numbered from 0. int a[5] gives you five ints called a[0] through a[4].

Declare, fill, print

#include <iostream>
using namespace std;

int main() {
    int a[5] = {10, 20, 30, 40, 50};

    for (int i = 0; i < 5; i++) {
        cout << "a[" << i << "] = " << a[i] << endl;
    }
    return 0;
}

Note the loop bound: i < 5, because the valid indices are 0..4. Writing i <= 5 would read a[5], which does not exist.

Reading into an array

Arrays shine when the input length is known first — read n, then n values:

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int a[100];
    for (int i = 0; i < n; i++) cin >> a[i];

    int sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    cout << "sum = " << sum << endl;
    return 0;
}

The array is declared bigger than needed (100) because C++ array sizes are fixed at compile time — you cannot resize one. This is exactly the shape of Array Maximum and Even and Odd Count.

The running maximum pattern

The most useful array pattern you will write a hundred times: carry a best value as you walk.

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int a[100];
    for (int i = 0; i < n; i++) cin >> a[i];

    int best = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] > best) best = a[i];
    }
    cout << "max = " << best << endl;
    return 0;
}

Seeding best with a[0] (not 0) is what makes all-negative input work. Seeding with 0 is the single most common bug in max problems — try it and watch this input fail.

Two-dimensional arrays

Rows and columns need two indices: a[row][col].

#include <iostream>
using namespace std;

int main() {
    int g[2][3] = {{1, 2, 3}, {4, 5, 6}};

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << g[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Convention matters: the first index is the row. Get it backwards and your grid prints transposed — see Matrix Transpose.

The three array bugs

Practice this lesson

These problems exercise exactly what you just read: