Back to Challenge Set 13

Debug Challenge: Arrays

Difficulty  

divider

Objective

Four short programs about arrays — Activities 1.23 and 1.24.

These four fail in four different ways. One will not compile. One crashes. One runs and gives a wrong answer with no warning at all. And one passes the test you would try first and crashes on a different one.

Part of each answer is saying which kind of failure it is— because the kind tells you where to look.


The Four Programs


Bug 1

This should say how many scores there are. It does not compile.

Bug 1
int[] scores = { 88, 92, 79, 95 };
Console.WriteLine($"There are {scores.length} scores.");

Bug 2

This should print the last name. It crashes.

Bug 2
string[] names = { "Avery", "Blake", "Casey" };
Console.WriteLine($"Last: {names[names.Length]}");

Also: the same mistake in exam notation, names[LENGTH(names)], is not a mistake at all. Say why.


Bug 3

This should make a backup, change the working copy, and leave the backup alone. Instead, this is what it prints:

Bug 3
int[] original = { 10, 20, 30 };
int[] backup = original;
original[0] = 999;
Console.WriteLine($"Working: {original[0]}, {original[1]}, {original[2]}");
Console.WriteLine($"Backup: {backup[0]}, {backup[1]}, {backup[2]}");
Output
Working: 999, 20, 30
Backup: 999, 20, 30

Also: written in exam notation as backup ← original, this program would work. Say what is different.


Bug 4

This should look up a seat and turn away seats that do not exist. Seats 1, 5, and 6 all behave correctly.

Bug 4
string[] seats = { "Avery", "Blake", "Casey", "Dakota", "Emery" };
Console.Write("Which seat? ");
int seat = int.Parse(Console.ReadLine());
if (seat <= seats.Length)
{
Console.WriteLine($"Seat {seat}: {seats[seat - 1]}");
}
else
{
Console.WriteLine($"There is no seat {seat}.");
}

Also: name the seat number that crashes it, and say why testing 1, 5, and 6 was not enough.


Submit

For each program, give:

  • Which kind of failure it is — will not compile, crashes, or runs and is wrong
  • One sentence on what was wrong
  • The corrected line, or lines, of code

Plus the three written answers, for Bugs 2, 3, and 4.

Work them out by reading first. Running the code tells you that something is wrong; it rarely tells you why, and on the exam there is no computer.

Commence Debugging