Back

Activity 1.24: Length and Safe Access

divider

Activity 1.24

Length and Safe Access

Key Concepts

How Long Is It?

The Last Index Is Length Minus One

Reading the Crash

Checking Before You Look

The Shell Game Only Worked With Three Cups

Activity 1.23's program said 3 in more places than one: Random.Shared.Next(0, 3) to hide the ball, cups[2] to show the last cup, and a swap that picked from 0, 1, or 2.

Add a fourth cup and every one of those is wrong — and nothing tells you. The ball can never land under the new cup, and the program runs as if nothing happened.

Challenge Set 12's Seat Finder had the other half of the problem: type seat 6 and the program crashes. It did not know how many seats there were, so it could not check.

Both are fixed by asking the array how long it is.

Every Array Knows Its Length

.Length after an array's name gives the number of elements in it. You never type the number yourself, so it is never out of date.

Demo
string[] crew = { "Ada", "Bo", "Cy" };
Console.WriteLine(crew.Length);
Console.WriteLine(crew[crew.Length - 1]);

Predict both lines. The second one is the one worth thinking about.

Every Array Knows Its Length

Demo
string[] crew = { "Ada", "Bo", "Cy" };
Console.WriteLine(crew.Length);
Console.WriteLine(crew[crew.Length - 1]);
Demo
3
Cy

Three elements, so crew.Length is 3. But the indexes are 0, 1, and 2 — there is no index 3, so the last element is at crew.Length - 1.

The Most Important Minus One

crew[crew.Length - 1] looks awkward. Learn to read it as one phrase: “the last one.”

It is right for an array of three, and it is still right after someone adds a fourth name to the list, because it asks the array instead of remembering a number. crew[2] is right for exactly one length.

Forgetting the minus one is the most common array bug there is, and the next slide is what it looks like.

Off the End, the Program Stops

Demo
string[] crew = { "Ada", "Bo", "Cy" };
Console.WriteLine(crew[3]);
Demo
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in Program.cs:line 3

C# refuses to read an element that is not there. It does not hand back a blank or a guess; it stops the program on the spot and tells you why.

Read It Like a Report

  • IndexOutOfRangeException — what went wrong: an index that does not exist in the array
  • Index was outside the bounds of the array. — the same thing in a sentence
  • line 3 — where the program was when it tried

Every crash in this course reads the same way: the name, the sentence, the line. Find all three before you change anything.

The Line That Crashes Is Not Always the Line That Is Wrong

Demo
string[] path = { "start", "empty", "gold", "trap", "exit" };
int position = 2;
int steps = 3;
position = position + steps;
Console.WriteLine(path[position]);
Demo
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in Program.cs:line 8

Line 8 only read the bad index. Line 6 made it: 2 plus 3 is 5, and a five-square path stops at index 4.

The Line That Crashes Is Not Always the Line That Is Wrong

The report tells you where the program noticed, not where the mistake was made. So the question to ask is not “what is wrong with line 8?” but “where did that index come from?”

Follow the variable backward, one assignment at a time, until you find the line that gave it a value it could not have. Today you do this with a real crash in a game you built.

Out of Range Has Two Ends

Demo
string[] crew = { "Ada", "Bo", "Cy" };
int i = -1;
Console.WriteLine(crew[i]);
Demo
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in Program.cs:line 5

Below zero is just as far outside as past the end. C# has no “count from the back” trick — crew[-1] is not the last element, it is a crash.

Check Before You Look

A valid index is at least 0 and less than the length. That is two comparisons, joined with Activity 1.15's &&, because an index can be wrong in two directions.

Demo
string[] crew = { "Ada", "Bo", "Cy" };
int i = 3;
if (i >= 0 && i < crew.Length)
{
Console.WriteLine(crew[i]);
}
else
{
Console.WriteLine($"No index {i}. Valid indexes are 0 to {crew.Length - 1}.");
}

Predict the output with i at 3, then at −1, then at 2.

Check Before You Look

i = 3, then -1, then 2
No index 3. Valid indexes are 0 to 2.
No index -1. Valid indexes are 0 to 2.
Cy

Two bad indexes turned away with a message, one good one read. The message uses crew.Length - 1, so it stays right when the array changes size.

Notice it is <, not <=. Write i <= crew.Length and index 3 gets through the check and crashes on the next line — the same off-by-one, hiding inside the check that was meant to stop it.

Today's Objectives

  • Finding how many elements an array holds
  • Reaching the last element without typing its index
  • Reading an IndexOutOfRangeException and tracing it back
  • Checking an index at both ends before using it

Key Terms

Length
The number of elements an array holds.
Off-by-one error
A mistake of exactly one position, usually at the start or end of a range.
Exception
The report C# gives when it stops a program, naming what went wrong and the line it happened on.
Bounds check
Testing that an index is valid before using it.

'F' → Fullscreen

divider

Build

Today you build a dungeon run in a new program named 1-24-dungeon-run. The path is an array of squares. Walk one square at a time or run two to four, dodge the traps, pick up the gold, and reach the exit.

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: The Path

  • Write the code below and run it. It only describes the path so far — the game starts in Task 2.
  • The first line never types the number 12. path.Length says how many squares there are, and path[path.Length - 1] is the last one.
  • Add two more squares to the array — "gold", "trap", just before "exit" — and run it again without changing anything else. Write down what the first line says now. Then take the two squares back out.
1-24-dungeon-run
string[] path = { "start", "empty", "gold", "trap", "empty", "gold", "trap", "empty", "gold", "trap", "gold", "exit" };
Console.WriteLine($"The path is {path.Length} squares long, and square {path.Length} is the {path[path.Length - 1]}.");
Console.WriteLine("Walking moves 1 square. Running moves 2 to 4. Every trap costs 1 health. Escape with as much gold as you can.");

Task 2: Walk or Run

  • position, health, and gold arrive with the game: where you are as an index, and what you have left.
  • The game loop keeps going while you are not yet on the last square and still have health. path.Length - 1 is the last index again — the exit.
  • Each turn moves position forward, then reads the square you landed on. Gold is picked up: the square is set to "empty", the way Activity 1.23 changed an element.
  • Play a game where you run on every turn. Sooner or later it crashes. When it does, write down the exception, the line number, and the square you were on before you change anything.
  • Then work out where the bad index came from. The crash names one line; the deck's “Not Always the Line That Is Wrong” slide says where to look instead.
1-24-dungeon-run
string[] path = { "start", "empty", "gold", "trap", "empty", "gold", "trap", "empty", "gold", "trap", "gold", "exit" };
int position = 0;
int health = 3;
int gold = 0;
Console.WriteLine($"The path is {path.Length} squares long, and square {path.Length} is the {path[path.Length - 1]}.");
Console.WriteLine("Walking moves 1 square. Running moves 2 to 4. Every trap costs 1 health. Escape with as much gold as you can.");
Console.WriteLine();
while (position < path.Length - 1 && health > 0)
{
Console.Write($"Square {position + 1}, health {health}, gold {gold}. Walk (1) or run (2)? ");
int choice = int.Parse(Console.ReadLine());
int steps = 1;
if (choice == 2)
{
steps = Random.Shared.Next(2, 5);
}
position = position + steps;
string square = path[position];
Console.WriteLine($" You move {steps} to square {position + 1}: {square}");
if (square == "trap")
{
health = health - 1;
}
if (square == "gold")
{
gold = gold + 1;
path[position] = "empty";
}
}
Console.WriteLine();
if (health > 0)
{
Console.WriteLine($"You escaped with {gold} gold!");
}
else
{
Console.WriteLine($"You collapsed on square {position + 1} with {gold} gold.");
}

Task 3: Stop at the Exit

  • Four lines fix it. If a run would carry you past the last square, you stop on the last square instead.
  • They go between the line that moves you and the line that reads the square — after the index is made, before it is used.
  • Run on every turn again, several games. It should never crash. Then play to win: write down your best gold.
1-24-dungeon-run
string[] path = { "start", "empty", "gold", "trap", "empty", "gold", "trap", "empty", "gold", "trap", "gold", "exit" };
int position = 0;
int health = 3;
int gold = 0;
Console.WriteLine($"The path is {path.Length} squares long, and square {path.Length} is the {path[path.Length - 1]}.");
Console.WriteLine("Walking moves 1 square. Running moves 2 to 4. Every trap costs 1 health. Escape with as much gold as you can.");
Console.WriteLine();
while (position < path.Length - 1 && health > 0)
{
Console.Write($"Square {position + 1}, health {health}, gold {gold}. Walk (1) or run (2)? ");
int choice = int.Parse(Console.ReadLine());
int steps = 1;
if (choice == 2)
{
steps = Random.Shared.Next(2, 5);
}
position = position + steps;
if (position > path.Length - 1)
{
position = path.Length - 1;
}
string square = path[position];
Console.WriteLine($" You move {steps} to square {position + 1}: {square}");
if (square == "trap")
{
health = health - 1;
}
if (square == "gold")
{
gold = gold + 1;
path[position] = "empty";
}
}
Console.WriteLine();
if (health > 0)
{
Console.WriteLine($"You escaped with {gold} gold!");
}
else
{
Console.WriteLine($"You collapsed on square {position + 1} with {gold} gold.");
}

Task 4: Scout Ahead

  • Twice a game, instead of moving, you can scout: type a square number and see what is on it. Knowing where the traps are is how you win with the most gold.
  • The player types a square number, so this is a bounds check in the player's numbers — 1 to path.Length, then look - 1 to read it. Activity 1.23's guess - 1, with a check in front.
  • This task wraps your walk-and-run code in an else. Select those lines and press Tab once to indent them; that is why so many lines are marked.
  • Test the scout with 0, 13, and −5 first — each should be turned away without using a scout — and then 1 and 12, which use up both. A fourth scout after that should say there are none left.
1-24-dungeon-run
string[] path = { "start", "empty", "gold", "trap", "empty", "gold", "trap", "empty", "gold", "trap", "gold", "exit" };
int position = 0;
int health = 3;
int gold = 0;
int scouts = 2;
Console.WriteLine($"The path is {path.Length} squares long, and square {path.Length} is the {path[path.Length - 1]}.");
Console.WriteLine("Walking moves 1 square. Running moves 2 to 4. Every trap costs 1 health. Escape with as much gold as you can.");
Console.WriteLine();
while (position < path.Length - 1 && health > 0)
{
Console.Write($"Square {position + 1}, health {health}, gold {gold}. Walk (1), run (2), or scout (3)? ");
int choice = int.Parse(Console.ReadLine());
if (choice == 3 && scouts > 0)
{
Console.Write(" Scout which square? ");
int look = int.Parse(Console.ReadLine());
if (look >= 1 && look <= path.Length)
{
Console.WriteLine($" Square {look} is {path[look - 1]}.");
scouts = scouts - 1;
}
else
{
Console.WriteLine($" There is no square {look}. The path is squares 1 to {path.Length}.");
}
}
else if (choice == 3)
{
Console.WriteLine(" No scouts left.");
}
else
{
int steps = 1;
if (choice == 2)
{
steps = Random.Shared.Next(2, 5);
}
position = position + steps;
if (position > path.Length - 1)
{
position = path.Length - 1;
}
string square = path[position];
Console.WriteLine($" You move {steps} to square {position + 1}: {square}");
if (square == "trap")
{
health = health - 1;
}
if (square == "gold")
{
gold = gold + 1;
path[position] = "empty";
}
}
}
Console.WriteLine();
if (health > 0)
{
Console.WriteLine($"You escaped with {gold} gold!");
}
else
{
Console.WriteLine($"You collapsed on square {position + 1} with {gold} gold.");
}

Task 5: Break It on Purpose

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

  1. Change the while condition's position < path.Length - 1 to position < path.Length. Play until you reach the exit, and keep going.
  2. Put it back. In the scout check, delete look >= 1 && and scout square 0. Put it back, then delete && look <= path.Length and scout square 13. Record the exception and line number both times.
  3. Put it back. On line 8, change path[path.Length - 1] to path[11]. It still works. Now delete "gold", just before "exit" in the array, and run it.

Number 1 never crashes, and that is what makes it worth noticing. Say why the game cannot end. For number 3, say which line crashed and why path[11] was right until the path changed.

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


Challenge (Optional): Thrown Back

  • Make traps throw you back two squares as well as costing health, and print the square you land on — its number and what is on it.
  • Then move a trap to square 2 and walk into it. Two squares back from square 2 is off the start of the path. Find out what happens, then add a check so nobody can ever be thrown off the start.
  • Add a comment saying which end of the array this protects, and which part of Task 3 protects the other one.
divider

Same Idea, Exam Notation

MeaningC#Exam notation
How many elementspath.LengthLENGTH(path)
The last elementpath[path.Length - 1]path[LENGTH(path)]
Add to the end—APPEND(path, "gold")
Insert at a position—INSERT(path, 3, "trap")
Remove at a position—REMOVE(path, 3)

1. The Last Element Has No Minus One

Exam lists start at 1, so the last element is at LENGTH(path) exactly. That is tidier than C#, and it is a trap in both directions: writing path[LENGTH(path) - 1] on the exam gets you the second to last, and writing path[path.Length] in C# crashes.

2. Exam Lists Can Grow and Shrink. C# Arrays Cannot.

A C# array is the size it was made, for as long as it exists — which is why your path could only change by editing the line that creates it. Exam lists change size:

  • APPEND adds to the end, and the length goes up by one.
  • INSERT(path, i, x) puts x at position i and shifts everything from there on one place right.
  • REMOVE(path, i) takes out position i and shifts everything after it one place left.

Both INSERT and REMOVE change the length, and they change which position everything after them is at. You will only ever read these on the exam, so trace them by writing the list out again after every line.

3. Going Off the End Stops the Program — in Both

The reference sheet is explicit: if an index is less than 1 or greater than the length of the list, an error is produced and the program terminates. That is exactly what C# did in Task 2. If an exam question walks a list one step too far, the answer is not a blank or a zero — nothing after that point happens at all.

divider

Checkpoint

One real game from the finished program, scouting twice. Your runs will move different distances.

Example Output
The path is 12 squares long, and square 12 is the exit.
Walking moves 1 square. Running moves 2 to 4. Every trap costs 1 health. Escape with as much gold as you can.
Square 1, health 3, gold 0. Walk (1), run (2), or scout (3)? 1 [Enter]
You move 1 to square 2: empty
Square 2, health 3, gold 0. Walk (1), run (2), or scout (3)? 1 [Enter]
You move 1 to square 3: gold
Square 3, health 3, gold 1. Walk (1), run (2), or scout (3)? 3 [Enter]
Scout which square? 4 [Enter]
Square 4 is trap.
Square 3, health 3, gold 1. Walk (1), run (2), or scout (3)? 2 [Enter]
You move 4 to square 7: trap
Square 7, health 2, gold 1. Walk (1), run (2), or scout (3)? 3 [Enter]
Scout which square? 9 [Enter]
Square 9 is gold.
Square 7, health 2, gold 1. Walk (1), run (2), or scout (3)? 2 [Enter]
You move 4 to square 11: gold
Square 11, health 2, gold 2. Walk (1), run (2), or scout (3)? 2 [Enter]
You move 2 to square 12: exit
You escaped with 2 gold!
  • The first line reports the path's length and last square without the number 12 typed anywhere
  • Running on every turn never crashes, and you land exactly on the exit
  • Scouting 0, 13, and −5 is turned away without using a scout; then 1 and 12 each show a square
  • You recorded the Task 1 line after adding squares, the Task 2 crash and where its index came from, your best gold, and all three Task 5 results
divider

Reflection

Answer the following questions before submitting your work.

  1. Why is path[path.Length - 1] better than path[11], even when the path happens to have twelve squares?
  2. Your Task 2 crash named the line that reads the square, but that line was not where the mistake was made. Explain where the bad index came from, and how Task 3's four lines stop it.
  3. On the exam, the last element of a list is aList[LENGTH(aList)], with no minus one. Explain why the exam and C# differ by one here, and which mistake you are more likely to make out of habit.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-24-dungeon-run program file.
  2. Your Task 2 crash — the exception, the line, the square — and where the bad index came from.
  3. Your best gold, your scout tests, and all three Task 5 results.
  4. Your three reflection answers.

Activity Complete