Back to Challenge Set 11

Debug Challenge: Loops

Difficulty  

divider

Objective

Four short programs about repetition — Activities 1.17 through 1.21.

All four of these compile. Not one of them produces an error, a warning, or a crash. Every one of them is wrong.

That is what makes loops worth a debug page of their own. A loop that repeats the wrong number of times, or changes the wrong variable, is still a perfectly legal loop — there is nothing for C# to object to, so you get a clean run and a confident wrong answer.

One of these never reaches the end, and it still is not an error. Part of this challenge is recognizing which one before you run it. If you do run it, Ctrl + C stops it.


The Four Programs


Bug 1

This should count down from 5 to 1 and then say liftoff. It prints forever.

Bug 1
int count = 5;
while (count > 0)
{
Console.WriteLine(count);
}
Console.WriteLine("Liftoff!");

Also: how would you know this loop never ends without running it? Say exactly what you looked for.


Bug 2

This should print the numbers 1 through 10. It prints 0 through 9.

Bug 2
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}

Also: there is more than one way to fix this one. Give two, and say which you would rather read.


Bug 3

This should add up 1 + 2 + 3 + 4 + 5 and print 15. It prints 5.

Bug 3
int total = 0;
for (int i = 1; i <= 5; i++)
{
total = i;
}
Console.WriteLine($"Total: {total}");

Bug 4

This should print a grid of stars — three rows of four. It prints twelve lines with one star on each.

Bug 4
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 4; col++)
{
Console.WriteLine("* ");
}
}

Also: the twelve is correct even though the output is not. Say where the twelve comes from.


Submit

For each program, give:

  • One sentence on what was wrong
  • The corrected line, or lines, of code

Plus the three written answers:

  • Bug 1 — what you look for to spot a loop that never ends, without running it
  • Bug 2 — two different fixes, and which you prefer
  • Bug 4 — where the twelve comes from

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