Arrays keep related values in order and let code read values by index.

array index Array indexes start at zero, so `scores[0]` reads the first value.

Arrays

bonus
arrays.cpp
Replay: real traced execution (multi-file project)
#include <iostream>

int main() {
    int scores[3] = {82, 91, 76};
    int bonus = 5;
    int firstScore = scores[0];
    int adjustedScore = scores[1] + bonus;

    std::cout << "first=" << firstScore << std::endl;
    std::cout << "adjusted=" << adjustedScore << std::endl;
    return 0;
}
#include <iostream>

int main() {
    int scores[3] = {82, 91, 76};
    int bonus = 0;
    int firstScore = scores[0];
    int adjustedScore = scores[1] + bonus;

    std::cout << "first=" << firstScore << std::endl;
    std::cout << "adjusted=" << adjustedScore << std::endl;
    return 0;
}
#include <iostream>

int main() {
    int scores[3] = {82, 91, 76};
    int bonus = 10;
    int firstScore = scores[0];
    int adjustedScore = scores[1] + bonus;

    std::cout << "first=" << firstScore << std::endl;
    std::cout << "adjusted=" << adjustedScore << std::endl;
    return 0;
}
  1. scores ← ⟨addr A⟩, bonus ← 5, firstScore ← 82, adjustedScore ← 96

    3int main() {4    int scores→ ⟨addr A⟩[3] = {82, 91, 76};5    int bonus→ 5 = 5; //@bonus=0, 106    int firstScore→ 82 = scores[0]82;7    int adjustedScore→ 96 = scores[1]91 + bonus5;89    std::cout << "first=" << firstScore82 << std::endl;10    std::cout << "adjusted=" << adjustedScore96 << std::endl;11    return 0;12}
    outputfirst=82
    adjusted=96
  1. scores ← ⟨addr A⟩, bonus ← 0, firstScore ← 82, adjustedScore ← 91

    3int main() {4    int scores→ ⟨addr A⟩[3] = {82, 91, 76};5    int bonus→ 0 = 0;6    int firstScore→ 82 = scores[0]82;7    int adjustedScore→ 91 = scores[1]91 + bonus0;89    std::cout << "first=" << firstScore82 << std::endl;10    std::cout << "adjusted=" << adjustedScore91 << std::endl;11    return 0;12}
    outputfirst=82
    adjusted=91
  1. scores ← ⟨addr A⟩, bonus ← 10, firstScore ← 82, adjustedScore ← 101

    3int main() {4    int scores→ ⟨addr A⟩[3] = {82, 91, 76};5    int bonus→ 10 = 10;6    int firstScore→ 82 = scores[0]82;7    int adjustedScore→ 101 = scores[1]91 + bonus10;89    std::cout << "first=" << firstScore82 << std::endl;10    std::cout << "adjusted=" << adjustedScore101 << std::endl;11    return 0;12}
    outputfirst=82
    adjusted=101

Follow the Array

  1. scores starts as 82, 91, and 76.
  2. bonus starts at 5.
  3. firstScore = scores[0] reads 82.
  4. adjustedScore = scores[1] + bonus adds 91 + 5.
  5. The program prints first=82 and adjusted=96. | bonus | first score | adjusted score | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |

Exercise: arrays.cpp

Reproduce first=82 and adjusted=96, then try bonus 0 and 10 and predict each adjusted score before running it.