Back

Activity 1.23: Arrays

divider

Activity 1.23

Arrays

Key Concepts

Many Values, One Name

Counting From Zero

Two Names, One Array

Your Fishing Trip Forgot Every Fish

Activity 1.20's program could tell you your biggest fish and your smallest. It could not tell you what you caught. Every fish was gone the moment the next one bit, because weight only ever held one.

Raylib Lab 5's challenge hit the same wall from the other side: shots counted hits, and all thirty-two invaders kept standing, because nothing in the program could remember which one was hit.

Both need one name that holds a whole list of values.

Your Fishing Trip Forgot Every Fish

Demo
int fish1 = 5;
int fish2 = 2;
int fish3 = 9;
int fish4 = 4;
int fish5 = 1;

This is how you would keep five fish with what you know so far. Now imagine ten casts, or a hundred — or a number of casts the player chooses, which you cannot know when you write the program. One variable per value does not scale.

One Name, Five Values

An array is a single variable that holds a whole row of values, in order. The square brackets after the type say “many of these”: int[] is an array of ints, and string[] is an array of strings.

The values go inside curly braces, separated by commas. To get one out, put its position in square brackets after the name. Predict what the two lines print.

One Name, Five Values

Demo
int[] catches = { 5, 2, 9, 4, 1 };
Console.WriteLine(catches[0]);
Console.WriteLine(catches[2]);
Demo
5
9

catches[0] is 5, the first fish. catches[2] is 9, the third. The number in the brackets is called the index, and it does not mean what you might expect.

C# Will Not Print the Whole Thing

Demo
int[] catches = { 5, 2, 9, 4, 1 };
Console.WriteLine(catches);
Demo
System.Int32[]

Printing the array prints what it is, not what is in it — “an array of 32-bit whole numbers,” which is C#'s full name for int. To see the values you print them one element at a time, which is exactly what today's game does with its three cups.

Counting From Zero

index: 0 1 2 3 4
value: 5 2 9 4 1

The first element is at index 0, not 1. The index counts how many steps you are from the start — and the first element is zero steps away.

So five elements means indexes 0 through 4. The last index is always one less than the number of elements.

Counting From Zero

Demo
int[] catches = { 5, 2, 9, 4, 1 };
Console.WriteLine(catches[5]);
Demo
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in Program.cs:line 3

There is no index 5, so C# stops the program and names the line. It will not guess what you meant. Activity 1.24 is about never getting here.

Counting From Zero

This feels wrong for about a week, and then it stops feeling like anything.

But people count cups from 1. Today's game shows the player “Cup 1, Cup 2, Cup 3,” and your program has to translate between the player's numbers and the array's every time it asks or answers.

The AP exam counts from 1, too. The panel below the Build deals with that, and it matters.

An Element Is a Variable

Demo
string[] crew = { "Ada", "Bo", "Cy" };
crew[1] = "Max";
Console.WriteLine($"{crew[0]} {crew[1]} {crew[2]}");
Demo
Ada Max Cy

crew[1] can be read like a variable and assigned like one. Assigning to it replaces that one element and leaves the others exactly where they were.

A Swap Needs a Third Hand

Today's game shuffles cups by swapping two elements. The obvious way is two lines: put the second cup into the first place, then the first cup into the second. Predict what is left.

Demo
cups[0] = cups[1];
cups[1] = cups[0];
Value Trace
cups[0] cups[1]
start BALL empty
cups[0] = cups[1] empty empty
cups[1] = cups[0] empty empty

The ball is gone. The first line overwrote the one value the second line needed, so both cups end up holding the same thing.

A Swap Needs a Third Hand

Demo
string held = cups[0];
cups[0] = cups[1];
cups[1] = held;
Value Trace
cups[0] cups[1] held
start BALL empty
held = cups[0] BALL empty BALL
cups[0] = cups[1] empty empty BALL
cups[1] = held empty BALL BALL

held keeps a copy of the first cup before it is overwritten — the way you would set one cup down on the table to swap two with one hand. Three lines, and every swap you ever write looks like this.

Now the Strange Part

Session 2 starts here. First, something you already know. Copy a number into a second variable, change the second one, and ask what the first one holds.

Demo
int a = 5;
int b = a;
b = 99;
Console.WriteLine($"b is {b}");
Console.WriteLine($"a is {a}");
Demo
b is 99
a is 5

int b = a; copied the 5. After that the two variables have nothing to do with each other.

Now the Strange Part

Now the same three steps with an array. Nothing on the fourth line touches a. Predict both lines before the output appears.

Demo
int[] a = { 1, 2, 3 };
int[] b = a;
b[0] = 99;
Console.WriteLine($"b[0] is {b[0]}");
Console.WriteLine($"a[0] is {a[0]}");
Demo
b[0] is 99
a[0] is 99

There is only one array. Both names point at it.

Two Labels on One Box

With a number, int b = a; copies the value. With an array, int[] b = a; copies the label: now there are two names stuck on the same box of values, and a change through either name is a change to the one box.

This is invisible until something changes — and then it is a bug that shows up far away from the line that caused it, in a variable you never touched.

Task 5 builds a cheat detector on exactly this mistake, and you get to watch it fail.

A Real Copy Is Built One Element at a Time

To get a second, independent array, make a new one and fill it with the values from the first. With three elements you can simply list them.

Demo
int[] a = { 1, 2, 3 };
int[] b = { a[0], a[1], a[2] };
b[0] = 99;
Console.WriteLine($"b[0] is {b[0]}");
Console.WriteLine($"a[0] is {a[0]}");
Demo
b[0] is 99
a[0] is 1

a[0], a[1], and a[2] are single values, so each one is copied the way a number is. Two boxes now, and changing one leaves the other alone.

The Exam Does the Opposite

On the AP exam, seen ← cups makes a real copy. The reference sheet says so in as many words.

So the same-looking line behaves one way in your programs and the other way on the exam. Nothing looks wrong in either, which is why the panel below the Build spells it out.

Today's Objectives

  • Creating an array and reading its elements by index
  • Explaining why the first index is 0
  • Assigning a new value to an element, and swapping two
  • Recognizing that two names can share one array
  • Making a copy that really is separate

Key Terms

Array
An ordered collection of values stored under one name.
Element
One value inside an array.
Index
The position of an element, counted from 0 in C#.
Reference
A name that points at an array rather than holding its own copy of it.

'F' → Fullscreen

divider

Build

Today you build a shell game in a new program named 1-23-shell-game: a ball under one of three cups, a shuffle you have to follow, and — in the second session — a dealer who cheats.

This activity runs over two sessions. Tasks 1 to 3 are the first; Tasks 4 to 6 are the second. The second session begins at the deck's “Now the Strange Part” slide.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.


Task 1: Three Cups

  • Write the code below and run it a few times. The ball lands under a different cup on different runs.
  • cups[ballAt] uses a variable as the index. Random.Shared.Next(0, 3) gives 0, 1, or 2 — exactly the three indexes this array has.
  • The screen says “Cup 1” and the code says cups[0]. The player counts from 1, the array counts from 0, and the display line is where the program translates.
  • Add Console.WriteLine(cups); as a last line, run it, and write down what it prints. Then delete it.
1-23-shell-game
string[] cups = { "empty", "empty", "empty" };
int ballAt = Random.Shared.Next(0, 3);
cups[ballAt] = "BALL";
Console.WriteLine("Watch the ball.");
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");

Task 2: Pick a Cup

  • Ask the player for a cup, check it, and then show all three so they can see they were right. Yes, this is easy — you can see the ball. Task 3 fixes that.
  • guess - 1 turns the player's cup number into an index. Cup 1 is cups[0], so the program always looks one lower than the number typed.
  • == compares the element with "BALL", the same way Activity 1.11 compared any two values.
1-23-shell-game
string[] cups = { "empty", "empty", "empty" };
int ballAt = Random.Shared.Next(0, 3);
cups[ballAt] = "BALL";
Console.WriteLine("Watch the ball.");
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");
Console.WriteLine();
Console.Write("Which cup has the ball? (1, 2, or 3) ");
int guess = int.Parse(Console.ReadLine());
if (cups[guess - 1] == "BALL")
{
Console.WriteLine("You found it!");
}
else
{
Console.WriteLine("Wrong cup.");
}
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");

Task 3: The Shuffle

  • Three swaps, each between two random cups. The while re-rolls second until it is a different cup from first, so every swap really moves something.
  • The three lines with held are the deck's swap, with first and second as the indexes.
  • first + 1 is the translation in the other direction: the program swaps indexes, and tells the player cup numbers.
  • Now it is a game. Watch where the ball starts, follow each swap, and pick a cup. Play five games and write down how many you won.
1-23-shell-game
string[] cups = { "empty", "empty", "empty" };
int ballAt = Random.Shared.Next(0, 3);
cups[ballAt] = "BALL";
Console.WriteLine("Watch the ball.");
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");
Console.WriteLine();
for (int swap = 1; swap <= 3; swap++)
{
int first = Random.Shared.Next(0, 3);
int second = Random.Shared.Next(0, 3);
while (second == first)
{
second = Random.Shared.Next(0, 3);
}
string held = cups[first];
cups[first] = cups[second];
cups[second] = held;
Console.WriteLine($"Swap {swap}: cup {first + 1} and cup {second + 1}");
}
Console.WriteLine();
Console.Write("Which cup has the ball? (1, 2, or 3) ");
int guess = int.Parse(Console.ReadLine());
if (cups[guess - 1] == "BALL")
{
Console.WriteLine("You found it!");
}
else
{
Console.WriteLine("Wrong cup.");
}
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");

Task 4: Break It on Purpose

The second session starts here. Three changes, one at a time. Write down exactly what happens, and put each one back before the next.

  1. Change cups[guess - 1] to cups[guess]. Play a game and pick the cup you know is right. Then play again and pick 3. Record what happens each time, including any line number.
  2. Put it back. Change line 3's Random.Shared.Next(0, 3) to Random.Shared.Next(1, 4) — “a cup from 1 to 3,” the way a person would say it. Run it ten times. Record where the ball starts, and what happens on some of the runs.
  3. Put it back. Delete the string held line and change cups[second] = held; to cups[second] = cups[first];. Play several games and count the balls in the final line each time.

Numbers 1 and 2 are the same mistake made in opposite directions. Say what the mistake is. For number 3, say why the ball can multiply as well as vanish.

There is no code block for this task. When it is over, your program is exactly what it was at the end of Task 3.


Task 5: The Dealer Cheats

  • Half the time, after the last swap, the dealer palms the ball: every cup is set to empty, so whatever you pick, you lose.
  • To catch him, seen saves the table right after the last swap, and the if at the bottom compares it with the table at the end. If any cup changed, the dealer cheated.
  • While testing, set cheatChance to 100 so the dealer cheats every game. Follow the ball carefully so you know he cheated.
  • Write down what the detector said. Then explain it using the deck's “Two Labels on One Box” slide. Leave cheatChance at 100 for Task 6.
1-23-shell-game
string[] cups = { "empty", "empty", "empty" };
int ballAt = Random.Shared.Next(0, 3);
cups[ballAt] = "BALL";
Console.WriteLine("Watch the ball.");
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");
Console.WriteLine();
for (int swap = 1; swap <= 3; swap++)
{
int first = Random.Shared.Next(0, 3);
int second = Random.Shared.Next(0, 3);
while (second == first)
{
second = Random.Shared.Next(0, 3);
}
string held = cups[first];
cups[first] = cups[second];
cups[second] = held;
Console.WriteLine($"Swap {swap}: cup {first + 1} and cup {second + 1}");
}
string[] seen = cups;
int cheatChance = 50;
if (Random.Shared.Next(1, 101) <= cheatChance)
{
cups[0] = "empty";
cups[1] = "empty";
cups[2] = "empty";
}
Console.WriteLine();
Console.Write("Which cup has the ball? (1, 2, or 3) ");
int guess = int.Parse(Console.ReadLine());
if (cups[guess - 1] == "BALL")
{
Console.WriteLine("You found it!");
}
else
{
Console.WriteLine("Wrong cup.");
}
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");
if (seen[0] != cups[0] || seen[1] != cups[1] || seen[2] != cups[2])
{
Console.WriteLine("The cups changed after the last swap. The dealer cheated!");
}

Task 6: Catch Him for Real

  • Change one line: build seen as a new array from the three values, the way the deck's last code slide did.
  • Play with cheatChance at 100 — the detector should speak every time. Then set it to 0 and play again — it should never accuse an honest dealer. Then put it back to 50.
  • Write a comment above the seen line explaining why the Task 5 version could never catch him.
1-23-shell-game
string[] cups = { "empty", "empty", "empty" };
int ballAt = Random.Shared.Next(0, 3);
cups[ballAt] = "BALL";
Console.WriteLine("Watch the ball.");
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");
Console.WriteLine();
for (int swap = 1; swap <= 3; swap++)
{
int first = Random.Shared.Next(0, 3);
int second = Random.Shared.Next(0, 3);
while (second == first)
{
second = Random.Shared.Next(0, 3);
}
string held = cups[first];
cups[first] = cups[second];
cups[second] = held;
Console.WriteLine($"Swap {swap}: cup {first + 1} and cup {second + 1}");
}
string[] seen = { cups[0], cups[1], cups[2] };
int cheatChance = 50;
if (Random.Shared.Next(1, 101) <= cheatChance)
{
cups[0] = "empty";
cups[1] = "empty";
cups[2] = "empty";
}
Console.WriteLine();
Console.Write("Which cup has the ball? (1, 2, or 3) ");
int guess = int.Parse(Console.ReadLine());
if (cups[guess - 1] == "BALL")
{
Console.WriteLine("You found it!");
}
else
{
Console.WriteLine("Wrong cup.");
}
Console.WriteLine($"Cup 1: {cups[0]} Cup 2: {cups[1]} Cup 3: {cups[2]}");
if (seen[0] != cups[0] || seen[1] != cups[1] || seen[2] != cups[2])
{
Console.WriteLine("The cups changed after the last swap. The dealer cheated!");
}

Challenge (Optional): Best of Five

  • Wrap the game in a for loop that plays five rounds, and keep a score of how many times the player found the ball. Print the score at the end.
  • Decide where cups is declared — inside the rounds loop or above it. Try the other one too, and say what happens to the table by round 5.
divider

Same Idea, Exam Notation

Two things are different here, and both will cost you points if you read past them.

C#
string[] cups = { "empty", "BALL", "empty" };
string middle = cups[1];
string[] seen = cups;
Exam Notation
cups ← ["empty", "BALL", "empty"]
middle ← cups[2]
seen ← cups

Lists are written with square brackets, [ ], rather than C#'s curly braces, and they have no type, because nothing on the reference sheet does.

1. Lists Start at 1

cups[1] on the exam is the first element. In C#, cups[1] is the second. That is why the middle cup is cups[1] on the left and cups[2] on the right.

First elementLast element of a 3-item list
C#cups[0]cups[2]
Exam notationcups[1]cups[3]

The exam counts the way your player does. Your game needed guess - 1 because C# does not; in exam notation, cups[guess] would have been right. When you trace one of these, write the positions out as 1, 2, 3, and do not let your C# habit answer for you.

2. The Arrow Makes a Real Copy

seen ← cups gives you an independent copy. The reference sheet says so outright. Change cups and seen keeps its values.

C# does the opposite, as Task 5 proved. Same-looking line, opposite behavior:

seen = cups, then change cups
C#seen changes too — one array, two names
Exam notationseen is unaffected — two separate lists

Written in exam notation, Task 5's detector would have worked. This is the subtlest difference in the whole course, because nothing looks wrong. If an exam question copies a list and then changes one of them, the other keeps its values. Answering from C# habit gets it backwards.

divider

Checkpoint

Two real games from the finished program. Your cups and swaps will be different. Follow the ball through the swaps in each one before reading the result.

An honest dealer
Watch the ball.
Cup 1: BALL Cup 2: empty Cup 3: empty
Swap 1: cup 2 and cup 1
Swap 2: cup 2 and cup 3
Swap 3: cup 2 and cup 3
Which cup has the ball? (1, 2, or 3) 2 [Enter]
You found it!
Cup 1: empty Cup 2: BALL Cup 3: empty
cheatChance at 100
Watch the ball.
Cup 1: BALL Cup 2: empty Cup 3: empty
Swap 1: cup 1 and cup 3
Swap 2: cup 2 and cup 1
Swap 3: cup 2 and cup 1
Which cup has the ball? (1, 2, or 3) 3 [Enter]
Wrong cup.
Cup 1: empty Cup 2: empty Cup 3: empty
The cups changed after the last swap. The dealer cheated!
  • The ball lands under a random cup, and the three swaps move it where the swap lines say
  • Picking the cup you followed it to wins against an honest dealer
  • With cheatChance at 100 the detector catches the dealer every game, and at 0 it never accuses him
  • You recorded what Console.WriteLine(cups); printed, your five-game score, all three Task 4 results, and what the Task 5 detector said
divider

Reflection

Answer the following questions before submitting your work.

  1. Cup 1 on the screen is cups[0] in your program. Explain why your guess needed - 1, and what the last index of an array of a hundred elements would be.
  2. Your Task 5 detector never caught the dealer. Explain what string[] seen = cups; actually did, and why building seen from cups[0], cups[1], and cups[2] fixed it.
  3. On the exam, seen ← cups makes a real copy. Describe a question you could get wrong by answering from C# habit.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-23-shell-game program file.
  2. What Console.WriteLine(cups); printed, and your five-game score from Task 3.
  3. All three Task 4 results, and what the Task 5 detector said — with your explanation.
  4. Your three reflection answers.

Activity Complete