Foundations
Arrays
Arrays keep related values in order and let code read them by index.
array index
Array indexes start at zero, so `scores[0]` reads the first value.
Arrays
Arrays.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int[] scores = { 82, 91, 76 };
int bonus = 5;
int firstScore = scores[0];
int adjustedScore = scores[1] + bonus;
Console.WriteLine($"first={firstScore}");
Console.WriteLine($"adjusted={adjustedScore}");
}
}
using System;
class Program
{
static void Main()
{
int[] scores = { 82, 91, 76 };
int bonus = 0;
int firstScore = scores[0];
int adjustedScore = scores[1] + bonus;
Console.WriteLine($"first={firstScore}");
Console.WriteLine($"adjusted={adjustedScore}");
}
}
using System;
class Program
{
static void Main()
{
int[] scores = { 82, 91, 76 };
int bonus = 10;
int firstScore = scores[0];
int adjustedScore = scores[1] + bonus;
Console.WriteLine($"first={firstScore}");
Console.WriteLine($"adjusted={adjustedScore}");
}
}
bonus ← 5, firstScore ← 82, adjustedScore ← 96
4{5 static void Main()6 {7 int[] scores = { 82, 91, 76 };8 int bonus→ 5 = 5; //@bonus=0, 109 int firstScore→ 82 = scores[0]82;10 int adjustedScore→ 96 = scores[1]91 + bonus5;1112 Console.WriteLine($"first={firstScore82}");13 Console.WriteLine($"adjusted={adjustedScore96}");14 }outputfirst=82 adjusted=96
bonus ← 0, firstScore ← 82, adjustedScore ← 91
4{5 static void Main()6 {7 int[] scores = { 82, 91, 76 };8 int bonus→ 0 = 0;9 int firstScore→ 82 = scores[0]82;10 int adjustedScore→ 91 = scores[1]91 + bonus0;1112 Console.WriteLine($"first={firstScore82}");13 Console.WriteLine($"adjusted={adjustedScore91}");14 }outputfirst=82 adjusted=91
bonus ← 10, firstScore ← 82, adjustedScore ← 101
4{5 static void Main()6 {7 int[] scores = { 82, 91, 76 };8 int bonus→ 10 = 10;9 int firstScore→ 82 = scores[0]82;10 int adjustedScore→ 101 = scores[1]91 + bonus10;1112 Console.WriteLine($"first={firstScore82}");13 Console.WriteLine($"adjusted={adjustedScore101}");14 }outputfirst=82 adjusted=101
Follow the Array
scoresstarts as82,91, and76.bonusstarts at5.firstScorereads82.adjustedScoreadds91 + 5.- The program prints
first=82andadjusted=96. | bonus | firstScore | adjustedScore | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |
Exercise: Arrays.cs
Reproduce first=82 and adjusted=96, then use the pinned bonuses 0 and 10 to predict each adjusted score.