← C++ tutorial

C++

Arrays

An array holds a fixed number of same-typed values: int numbers[5] = {1, 2, 3, 4, 5};.

Example: manually tracking the length

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    int total = 0;
    for (int i = 0; i < 5; i++) {
        total += numbers[i];
    }
    cout << "Total: " << total << endl;
    return 0;
}
Total: 15

Notice the loop condition is hardcoded as i < 5, matching the array's known size. Unlike Java's numbers.length, a plain C++ array doesn't know its own length at all — the size has to be tracked separately by whoever's using it, which is exactly the kind of manual bookkeeping that modern C++ code more often avoids with a std::vector instead, a topic for a later lesson.

Example
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    int total = 0;
    for (int i = 0; i < 5; i++) {
        total += numbers[i];
    }
    cout << "Total: " << total << endl;
    return 0;
}
Output
Total: 15