Back to Challenge Set 17

Debug Challenge: Scope

Difficulty  

divider

Objective

Four short programs about where a variable lives — Activity 2.5.

One will not build. One builds with a warning, and the warning is the whole clue. Two run cleanly and give a wrong answer with no warning at all.

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 print the price with tax, twice. It does not build.

Bug 1
Console.WriteLine(AddTax(50));
Console.WriteLine(taxed);
double AddTax(double price)
{
double taxed = price * 1.08;
return taxed;
}

Also: say in one sentence where taxed actually exists, and for how long.


Bug 2

This should add 5 to the running total. It builds with no warning, and the total never changes:

Bug 2
int total = 100;
AddFee(total);
Console.WriteLine(total);
void AddFee(int total)
{
total = total + 5;
}
Output
100

Also: there are two totals in this program. Say which one line 8 changes.


Bug 3

This should use the shop's 8% rate, so 100 should cost 108. It builds with one warning on line 1, and prints:

Bug 3
double rate = 0.08;
Console.WriteLine(PriceWithTax(100));
double PriceWithTax(double amount)
{
double rate = 0.2;
return amount * (1 + rate);
}
Output
120

Also: both rates are written down and neither is a typo. Say what decides which one the method uses — and what the warning on line 1 was trying to tell you.


Bug 4

This should count three calls: 1, 2, 3. It prints:

Bug 4
Record();
Record();
Record();
void Record()
{
int count = 0;
count = count + 1;
Console.WriteLine(count);
}
Output
1
1
1

Also: say when count is created and when it is thrown away, and why that gives 1 every time.


Submit

For each program, give:

  • Which kind of failure it is — will not build, builds with a warning, or runs and is wrong
  • One sentence on what was wrong
  • The corrected line, or lines, of code

Plus the four written answers.

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