Foundations
Arrays
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
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;
}
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
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
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
scoresstarts as82,91, and76.bonusstarts at5.firstScore = scores[0]reads82.adjustedScore = scores[1] + bonusadds91 + 5.- The program prints
first=82andadjusted=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.