Back

Activity 1.25: Walking Through an Array

divider

Activity 1.25

Walking Through an Array

Key Concepts

One Loop, Every Element

The Standard Traversal

One Step Too Far

The Loop Patterns, on Real Data

Two Arrays, One Index

Nothing So Far Has Looked at Every Element

Activity 1.24's game loop moved through the path, but it only ever read the square you landed on. Activity 1.23 showed each cup with a line of its own.

That works for three elements and nothing else. Here is the 1.23 way of showing a whole array.

Nothing So Far Has Looked at Every Element

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

One line per element. A hundred names would need a hundred lines, and an array whose length you do not know until the program runs cannot be written this way at all.

One Loop Visits Every Element

Activity 1.19's for loop counts. Point the count at the indexes — start at 0, stop before .Length — and crew[i] is a different element on every pass.

Visiting every element of an array in order is called a traversal.

One Loop Visits Every Element

Demo
string[] crew = { "Ada", "Bo", "Cy" };
for (int i = 0; i < crew.Length; i++)
{
Console.WriteLine(crew[i]);
}
Demo
Ada
Bo
Cy

The same output from three lines that never change. Add a hundred names to the array and the loop shows all of them.

Read the Header as One Phrase

for (int i = 0; i < crew.Length; i++) is in more programs than any other line in this course. Every piece of it is there for a reason:

  • int i = 0 — start at 0, the first index
  • i < crew.Length — stop before the length, so the last pass is crew.Length - 1, the last index from Activity 1.24
  • i++ — one index at a time, so nothing is skipped

Learn it as one phrase: “for every index in crew.”

One Character Too Far

Change < to <= and the loop takes exactly one more pass. Predict what happens on it.

Demo
string[] crew = { "Ada", "Bo", "Cy" };
for (int i = 0; i <= crew.Length; i++)
{
Console.WriteLine(crew[i]);
}

One Character Too Far

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

All three names print, and then it crashes. The extra pass has i at 3, and there is no crew[3]— Activity 1.24's exception, from a loop this time.

The Classic Off-By-One

<= in a traversal is the most common array bug there is. It comes from reading crew.Length as “the last index,” which it is not — it is one past it.

C# catches it for you: the program stops at the first index that does not exist, and the report names the line. You will make this crash on purpose today.

Number Them for People

i starts at 0, but people count from 1. Show i + 1 next to the element, the way Activity 1.24 showed square numbers.

Demo
string[] crew = { "Ada", "Bo", "Cy" };
for (int i = 0; i < crew.Length; i++)
{
Console.WriteLine($"{i + 1}. {crew[i]}");
}

Number Them for People

Demo
string[] crew = { "Ada", "Bo", "Cy" };
for (int i = 0; i < crew.Length; i++)
{
Console.WriteLine($"{i + 1}. {crew[i]}");
}
Demo
1. Ada
2. Bo
3. Cy

i is the index; i + 1 is the number a person reads. The array itself never changes.

The Loop Patterns, on Real Data

Activity 1.20's accumulator added up numbers the loop made itself. Point it at an array and it adds up data.

Demo
int[] scores = { 7, 9, 6, 10 };
int total = 0;
for (int i = 0; i < scores.Length; i++)
{
total = total + scores[i];
}
Console.WriteLine($"Total: {total}");

Predict the total.

The Loop Patterns, on Real Data

Demo
int[] scores = { 7, 9, 6, 10 };
int total = 0;
for (int i = 0; i < scores.Length; i++)
{
total = total + scores[i];
}
Console.WriteLine($"Total: {total}");
Demo
Total: 32

7 + 9 + 6 + 10. Start the total above the loop, add one element per pass — the same shape as 1.20, now walking an array.

Keep the Best, and Where It Was

Activity 1.20 kept the biggest value. With an array you can keep its position instead: best holds an index, and scores[best] is the value at it.

Demo
int[] scores = { 7, 9, 6, 10, 8 };
int best = 0;
for (int i = 0; i < scores.Length; i++)
{
if (scores[i] > scores[best])
{
best = i;
}
}
Console.WriteLine($"Best: round {best + 1}, with {scores[best]}");

Keep the Best, and Where It Was

Demo
int[] scores = { 7, 9, 6, 10, 8 };
int best = 0;
for (int i = 0; i < scores.Length; i++)
{
if (scores[i] > scores[best])
{
best = i;
}
}
Console.WriteLine($"Best: round {best + 1}, with {scores[best]}");
Demo
Best: round 4, with 10

best starts at 0, the first element — a real score from the array, never a guessed number like 1.20's starting values. Knowing where tells you which round, not just how good it was.

An Array You Fill Yourself

So far every array was written out in full. new int[4] makes an array of four with nothing chosen yet— predict what is in it.

Demo
int[] squares = new int[4];
for (int i = 0; i < squares.Length; i++)
{
Console.Write($"{squares[i]} ");
}
Demo
0 0 0 0

Every element of a new int array starts at 0. Its length is fixed at 4 the moment it is made.

An Array You Fill Yourself

A loop can write each element too: squares[i] = ... on the left of the =, the way Activity 1.23 changed one cup.

Demo
int[] squares = new int[4];
for (int i = 0; i < squares.Length; i++)
{
squares[i] = (i + 1) * (i + 1);
}
for (int i = 0; i < squares.Length; i++)
{
Console.Write($"{squares[i]} ");
}
Demo
1 4 9 16

Two Arrays, One Index

When two arrays line up — the first name goes with the first age — one i reaches the matching element in both.

Demo
string[] names = { "Ada", "Bo", "Cy" };
int[] ages = { 15, 17, 16 };
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"{names[i]} is {ages[i]}");
}
Demo
Ada is 15
Bo is 17
Cy is 16

This is why the index matters. Today your arrows and your rival's line up end by end, and one i compares them.

Today's Objectives

  • Writing the standard traversal, and why its test is <
  • Filling an array inside a loop
  • Totaling, counting, and keeping the best — with its position
  • Walking two arrays with one index

Key Terms

Traversal
Visiting every element of an array in order.
Off-by-one error
A loop that runs one pass too many or too few, usually from <= where < belongs.
Parallel arrays
Two arrays where the same index means the same thing in both.
Linear search
Checking elements one at a time, in order, until the one you want turns up.

'F' → Fullscreen

divider

Build

Today you shoot an archery final in a new program named 1-25-archery-final. Your rival has already shot six ends, one arrow each, and their scores are an array. You shoot six of your own — steady, or going for gold — and the program works out who won.

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 Rival's Scorecard

  • Write the code below and run it. One loop shows all six ends, numbered from 1 with i + 1.
  • Change < to <= and run it. Write down how many ends printed before the crash, the exception, and the line number. Then change it back.
  • Give your rival a seventh end: add , 10 to the end of the array and run it. Write down what changed — and notice you did not touch the loop. Then take it back out.
1-25-archery-final
int[] rival = { 7, 9, 6, 8, 7, 6 };
Console.WriteLine($"Archery final: {rival.Length} ends, one arrow each. Your rival has already shot:");
for (int i = 0; i < rival.Length; i++)
{
Console.WriteLine($" End {i + 1}: {rival[i]}");
}

Task 2: Your Arrows

  • mine is made with new int[rival.Length]: the same number of ends as your rival, every score starting at 0.
  • The second loop writes into the array. Each pass shows the rival's score for that end, asks how you shoot, and stores your arrow in mine[i]. rival[i] and mine[i] are the same end, because they share i.
  • A steady shot scores 6 to 8. Going for gold scores anywhere from 4 to 10. Play a few rounds and decide when each one is worth it.
1-25-archery-final
int[] rival = { 7, 9, 6, 8, 7, 6 };
int[] mine = new int[rival.Length];
Console.WriteLine($"Archery final: {rival.Length} ends, one arrow each. Your rival has already shot:");
for (int i = 0; i < rival.Length; i++)
{
Console.WriteLine($" End {i + 1}: {rival[i]}");
}
Console.WriteLine();
Console.WriteLine("Your turn. A steady shot scores 6 to 8. Going for gold scores anywhere from 4 to 10.");
Console.WriteLine();
for (int i = 0; i < mine.Length; i++)
{
Console.Write($"End {i + 1} (rival {rival[i]}): steady (1) or go for gold (2)? ");
int choice = int.Parse(Console.ReadLine());
if (choice == 2)
{
mine[i] = Random.Shared.Next(4, 11);
}
else
{
mine[i] = Random.Shared.Next(6, 9);
}
Console.WriteLine($" You shot {mine[i]}.");
}

Task 3: The Result

  • A third loop walks both arrays after the shooting is over. Two accumulators total each archer, and a counter counts the ends you won — Activity 1.20's patterns, on your own data.
  • mine[i] > rival[i] compares the same end in both arrays. That needs the index; the values alone would not say which arrow goes with which.
  • A tie on total goes to a shoot-off. Play until you have won the final at least once, and write down the score.
1-25-archery-final
int[] rival = { 7, 9, 6, 8, 7, 6 };
int[] mine = new int[rival.Length];
Console.WriteLine($"Archery final: {rival.Length} ends, one arrow each. Your rival has already shot:");
for (int i = 0; i < rival.Length; i++)
{
Console.WriteLine($" End {i + 1}: {rival[i]}");
}
Console.WriteLine();
Console.WriteLine("Your turn. A steady shot scores 6 to 8. Going for gold scores anywhere from 4 to 10.");
Console.WriteLine();
for (int i = 0; i < mine.Length; i++)
{
Console.Write($"End {i + 1} (rival {rival[i]}): steady (1) or go for gold (2)? ");
int choice = int.Parse(Console.ReadLine());
if (choice == 2)
{
mine[i] = Random.Shared.Next(4, 11);
}
else
{
mine[i] = Random.Shared.Next(6, 9);
}
Console.WriteLine($" You shot {mine[i]}.");
}
int myTotal = 0;
int rivalTotal = 0;
int endsWon = 0;
for (int i = 0; i < mine.Length; i++)
{
myTotal = myTotal + mine[i];
rivalTotal = rivalTotal + rival[i];
if (mine[i] > rival[i])
{
endsWon = endsWon + 1;
}
}
Console.WriteLine();
Console.WriteLine($"Final score: you {myTotal}, rival {rivalTotal}. You won {endsWon} of {mine.Length} ends.");
if (myTotal > rivalTotal)
{
Console.WriteLine("You win the final!");
}
else if (myTotal < rivalTotal)
{
Console.WriteLine("Your rival takes the final.");
}
else
{
Console.WriteLine("A tie. It goes to a shoot-off.");
}

Task 4: Your Best Arrow

  • Keep the position of your best arrow, not just its score. best starts at 0 — your first arrow — and moves whenever a later arrow beats mine[best].
  • The results line uses best + 1 for the end number and mine[best] for the score.
  • Before you run it, look at your arrows from the last game and predict which end it will name if two arrows tie for best. Then find out.
1-25-archery-final
int[] rival = { 7, 9, 6, 8, 7, 6 };
int[] mine = new int[rival.Length];
Console.WriteLine($"Archery final: {rival.Length} ends, one arrow each. Your rival has already shot:");
for (int i = 0; i < rival.Length; i++)
{
Console.WriteLine($" End {i + 1}: {rival[i]}");
}
Console.WriteLine();
Console.WriteLine("Your turn. A steady shot scores 6 to 8. Going for gold scores anywhere from 4 to 10.");
Console.WriteLine();
for (int i = 0; i < mine.Length; i++)
{
Console.Write($"End {i + 1} (rival {rival[i]}): steady (1) or go for gold (2)? ");
int choice = int.Parse(Console.ReadLine());
if (choice == 2)
{
mine[i] = Random.Shared.Next(4, 11);
}
else
{
mine[i] = Random.Shared.Next(6, 9);
}
Console.WriteLine($" You shot {mine[i]}.");
}
int myTotal = 0;
int rivalTotal = 0;
int endsWon = 0;
int best = 0;
for (int i = 0; i < mine.Length; i++)
{
myTotal = myTotal + mine[i];
rivalTotal = rivalTotal + rival[i];
if (mine[i] > rival[i])
{
endsWon = endsWon + 1;
}
if (mine[i] > mine[best])
{
best = i;
}
}
Console.WriteLine();
Console.WriteLine($"Final score: you {myTotal}, rival {rivalTotal}. You won {endsWon} of {mine.Length} ends.");
Console.WriteLine($"Your best arrow was end {best + 1}: {mine[best]}.");
if (myTotal > rivalTotal)
{
Console.WriteLine("You win the final!");
}
else if (myTotal < rivalTotal)
{
Console.WriteLine("Your rival takes the final.");
}
else
{
Console.WriteLine("A tie. It goes to a shoot-off.");
}

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. In the shooting loop, change i < mine.Length to i <= mine.Length. Shoot all your ends.
  2. Put it back. In the results loop, change int i = 0 to int i = 1 — the way exam lists are numbered. Play a game and add up both totals yourself from the scorecard.
  3. Put it back. Change new int[rival.Length] to new int[6]. It still works. Now give your rival a seventh end of 10, as in Task 1, and play.

Only number 1 crashes. Numbers 2 and 3 give a wrong answer and no error at all. For each, say which total is wrong and by how much. For number 3, say which line the rival's seventh end should have 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): Find a Score

  • After the results, ask the player for a score and report the first end where they shot it — or say they never did.
  • You need a variable that remembers where you found it, set before the loop. “Never” is only knowable once the loop has finished, so the message comes after it, not inside.
  • Checking elements one at a time like this is a linear search, the first named algorithm on the AP exam. Make sure two matching arrows report the first one.
divider

Same Idea, Exam Notation

The exam walks a list two ways. Neither one is a for header: the reference sheet has no counting loop.

C#
for (int i = 0; i < crew.Length; i++)
{
Console.WriteLine(crew[i]);
}
Exam: FOR EACH
FOR EACH name IN crew
{
DISPLAY(name)
}
Exam: with the position
i ← 1
REPEAT LENGTH(crew) TIMES
{
DISPLAY(crew[i])
i ← i + 1
}

1. FOR EACH Hands You the Elements

FOR EACH name IN crew sets name to each element in turn, first to last. There is no index at all, so it cannot go off the end — and it cannot tell you which position it is on. You will read and write it on the exam; C# has one too, and you will meet it later in the course.

2. When the Position Matters, the Counter Is Hand-Made

Anything that needs the index — your best end, or matching two lists end by end — is written with REPEAT LENGTH(crew) TIMES and a counter kept by hand, exactly as Activity 1.19 showed.

3. Same Elements, Different Numbers

C# starts at 0 and stops before the length. The exam starts at 1 and repeats LENGTH times. Both visit every element exactly once. Task 5's number 2 is what happens when the exam's habit leaks into C#: int i = 1 quietly skips your first end, and nothing warns you.

divider

Checkpoint

One real final from the finished program. Your arrows will be different.

Example Output
Archery final: 6 ends, one arrow each. Your rival has already shot:
End 1: 7
End 2: 9
End 3: 6
End 4: 8
End 5: 7
End 6: 6
Your turn. A steady shot scores 6 to 8. Going for gold scores anywhere from 4 to 10.
End 1 (rival 7): steady (1) or go for gold (2)? 1 [Enter]
You shot 6.
End 2 (rival 9): steady (1) or go for gold (2)? 2 [Enter]
You shot 9.
End 3 (rival 6): steady (1) or go for gold (2)? 1 [Enter]
You shot 8.
End 4 (rival 8): steady (1) or go for gold (2)? 2 [Enter]
You shot 4.
End 5 (rival 7): steady (1) or go for gold (2)? 1 [Enter]
You shot 8.
End 6 (rival 6): steady (1) or go for gold (2)? 2 [Enter]
You shot 10.
Final score: you 45, rival 43. You won 3 of 6 ends.
Your best arrow was end 6: 10.
You win the final!
  • The scorecard prints every rival end without the number 6 typed anywhere
  • Your six arrows are stored, and the results compare them end by end
  • The best-arrow line names an end that really did score that
  • You recorded the Task 1 crash and seventh end, a winning score, and all three Task 5 results with how far off each total was
divider

Reflection

Answer the following questions before submitting your work.

  1. Explain why the traversal's test is i < mine.Length, and what your Task 5 crash showed happens with <=.
  2. Your results loop compares mine[i] with rival[i], and best keeps an index rather than a score. Explain why both need the position, not just the values.
  3. Starting the results loop at int i = 1 gave a wrong total and no error. Explain where that habit comes from, and why the exam's list starting at 1 still visits every element.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-25-archery-final program file.
  2. Your Task 1 results — the crash and the seventh end — and a winning final score.
  3. All three Task 5 results, with how far off each total was.
  4. Your three reflection answers.

Activity Complete