Loading...

C++ Arrays

This page keeps the twenty lines from the constants page and adds two lines under them. That page ended with pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, and 20. That twenty-line screen is the step this page builds on. The first box still holds the word pine, and the comment // the word stays pine still sits above the declarations.
This module stays on the same file. types.cpp keeps its name, its boxes, and its build command. The example adds one new array, named scores, which holds three int values. It also adds two writing lines that read two of its values. The rest of the file stays the same, so the new lines on the screen come only from the array.
Many programs need a list of values of the same kind. A class has a list of test scores, a game keeps the positions of its players, and a sensor records the last few readings. Writing a separate box for each value would make the code long and hard to change, so C++ offers an array, which is one name for a row of boxes with the same type.

An array is declared with the element type, a name, and a size in square brackets. The line int scores[3] = {4, 5, 6}; creates three int boxes in a row under the one name scores. The list in braces gives the starting values in order. The first box holds 4, the second holds 5, and the third holds 6. The size in the brackets must be fixed when the file is built, so the array cannot grow or shrink while the program runs. Each box in the row has the same type, which is why every value in scores is an int.
Each box has a position called an index. Indexes start at 0, not 1, and they count along the row. The first box is at index 0, the second at index 1, and the third at index 2. To read one value, write the name, then the index in square brackets. The expression scores[0] reads the first box and gives 4. The expression scores[2] reads the third box and gives 6. The index is an expression too, so scores[count] would read the box whose position is the current value of count, when that value is in range.

The last index of an array of three is 2, which is one less than the size. This rule follows from starting at 0. An array of ten items has indexes 0 through 9. The most common mistake with an array is an index that is one too large. Reading scores[3] in an array of three reads past the end of the row, and that is a bug, even though the compiler may build the file without a message. The program might print a random number or crash later in a confusing place. Stay inside the range from 0 to the size minus one, and the array is safe to use.
The index also works for writing. The line scores[1] = 9; replaces the value 5 in the middle box with 9. That write does not touch the first or third box. An array box can change, unlike a const box from the previous page, because scores was declared without const. Each read or write uses one index, and the boxes around it keep their values.

Type the file in this order, or add only the new lines if types.cpp is already on disk. Keep the twenty lines from the constants page. Under the const limit line, add one new array: int scores[3] = {4, 5, 6}; At the end of the writing lines, under the last limit line, add two lines: one for scores[0] and one for scores[2]. The checked file is below. The file name on disk stays types.cpp.

types.cpp adds an int array and two index lines to the twenty

cpp
#include <iostream>
#include <string>

int main()
{
    // the word stays pine
    std::string word = "pine";
    int count = 2;
    double ratio = 0.5;
    bool ready = true;
    double price = 7.9;
    const int limit = 10;
    int scores[3] = {4, 5, 6};
    std::string other = "cone";
    std::string joined = word + " " + other;
    std::cout << word << std::endl;
    std::cout << count << std::endl;
    std::cout << ratio << std::endl;
    std::cout << ready << std::endl;
    std::cout << word.size() << std::endl;
    std::cout << joined << std::endl;
    std::cout << word[0] << std::endl;
    std::cout << joined.find("cone") << std::endl;
    std::cout << joined.substr(5, 4) << std::endl;
    std::cout << count * 4 << std::endl;
    std::cout << 7 / 2 << std::endl;
    std::cout << 7.0 / 2 << std::endl;
    std::cout << (count > 1) << std::endl;
    std::cout << (count == 3) << std::endl;
    std::cout << !ready << std::endl;
    std::cout << static_cast<int>(price) << std::endl;
    std::cout << static_cast<double>(count) / 4 << std::endl;
    std::cout << static_cast<int>(ratio * 3) << std::endl;
    std::cout << limit << std::endl;
    std::cout << limit * count << std::endl;
    std::cout << scores[0] << std::endl;
    std::cout << scores[2] << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 types.cpp -o types and then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows twenty-two lines. The first twenty are the same as on the constants page. The twenty-first line is scores[0], which prints 4. The twenty-second line is scores[2], which prints 6.
Check the twenty-first line first. The first box of the row holds 4, and the screen shows 4. Then check the twenty-second line. The third box holds 6, and the screen shows 6, not 5. The middle box, at index 1, does not appear on the screen in this version of the file. The table gives each row its piece, so compare your run with it line by line. If the screen has more than twenty-two lines, check that no writing line was copied twice.

📊 Two array reads and what they show

Piece What the screen shows
First 4, scores[0] reads the first box
Last 6, scores[2] reads the last box of three
Rule indexes run from 0 to 2, because the size is 3
Screen pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20, 4, 6

Add the line scores[0] = 9; just before the two reads, then rebuild. The twenty-first line becomes 9, because the write runs first. Remove that write to return to 4. Next, read scores[3] in a new writing line and rebuild. The build may still succeed, which is what makes this bug hard to see, and the printed value is not one of the three boxes you declared. Delete that line before you leave, because the page must not keep a read past the end. Each experiment changes one thing, so the screen shows exactly which line caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
The next page is operators. It starts the Operators module, and its job is to use the remainder operator % and the shortcut += on int values in the same types.cpp file. This page stops before any operator other than the square brackets that read an index. You leave with twenty-two lines on the screen, the first box value 4, and the last box value 6. Count the lines before you leave. There are twenty-two, and the last one is 6.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top