Foundations
Arrays
An array stores a fixed number of same-typed elements next to each other.
array
`int scores[3]` creates storage for three integers.
index
Array indexes start at zero, so `scores[0]` is the first element.
Arrays
arrays.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int base = 80;
int scores[3] = {base, base + 10, base + 20};
int first = scores[0];
int last = scores[2];
int total = first + last;
printf("first=%d\n", first);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int base = 60;
int scores[3] = {base, base + 10, base + 20};
int first = scores[0];
int last = scores[2];
int total = first + last;
printf("first=%d\n", first);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int base = 90;
int scores[3] = {base, base + 10, base + 20};
int first = scores[0];
int last = scores[2];
int total = first + last;
printf("first=%d\n", first);
printf("total=%d\n", total);
return 0;
}
base ← 80, scores ← ⟨addr A⟩, first ← 80, last ← 100, total ← 180
3int main(void) {4 int base→ 80 = 80; //@base=60, 905 int scores→ ⟨addr A⟩[3] = {base80, base + 10, base + 20};6 int first→ 80 = scores[0]80;7 int last→ 100 = scores[2]100;8 int total→ 180 = first80 + last100;910 printf("first=%d\n", first80);11 printf("total=%d\n", total180);12 return 0;13}outputfirst=80 total=180
base ← 60, scores ← ⟨addr A⟩, first ← 60, last ← 80, total ← 140
3int main(void) {4 int base→ 60 = 60;5 int scores→ ⟨addr A⟩[3] = {base60, base + 10, base + 20};6 int first→ 60 = scores[0]60;7 int last→ 80 = scores[2]80;8 int total→ 140 = first60 + last80;910 printf("first=%d\n", first60);11 printf("total=%d\n", total140);12 return 0;13}outputfirst=60 total=140
base ← 90, scores ← ⟨addr A⟩, first ← 90, last ← 110, total ← 200
3int main(void) {4 int base→ 90 = 90;5 int scores→ ⟨addr A⟩[3] = {base90, base + 10, base + 20};6 int first→ 90 = scores[0]90;7 int last→ 110 = scores[2]110;8 int total→ 200 = first90 + last110;910 printf("first=%d\n", first90);11 printf("total=%d\n", total200);12 return 0;13}outputfirst=90 total=200
Follow the Array
basestarts at80.- The scores are
80,90, and100. firstreads the first score,80.lastreads the last score,100.total = first + lastbecomes180, so the program printsfirst=80andtotal=180. | base | scores | first | total | | --- | --- | --- | --- | | 60 | 60, 70, 80 | 60 | 140 | | 80 | 80, 90, 100 | 80 | 180 | | 90 | 90, 100, 110 | 90 | 200 |
Exercise: arrays.c
Reproduce first=80 and total=180, then use the pinned base values 60 and 90 to predict each first score and total.