We had all the First Year students in for their first lab today. As part of the fun we ask the students to find the bug in this piece of C# code, which is supposed to add two numbers together.
1: static void Main()
3: Console.WriteLine("This program adds two numbers together");
4: Console.Write("First Number : ");
5: string number1Text = Console.ReadLine();
6: int number1 = int.Parse(number1Text);
7: Console.Write("Second Number : ");
8: string number2Text = Console.ReadLine();
9: int number2 = int.Parse(number2Text);
10: int result = number1 * number2;
11: Console.WriteLine("Sum is : " + result );
Lots of people found the error straight away. But some people (usually the more advanced programmers) didn’t. I had reports describing problems with number parsing, the range of the input values, crashes caused by entering text instead of numbers, and all sorts of things like that. But the real problem is much, much simpler.
The program says it adds two numbers. But the statement at line 10 which works out the result actually does a multiplication rather than an addition. Which means that the program is completely correct, runs fine, but does the wrong thing. This is a surprisingly common problem with programs. You can write a program that is perfect, works a treat, but doesn’t do what the customer wants. And you will not get paid/get fired as a result.
The nice thing about this “sneaky” lab for me is that it worked on two levels. Those learning how to program can see how the computer follows a sequence of statements, executing each in turn. If the statement is wrong, the output is wrong. Those who can program a bit have hopefully learnt that it is a good idea to read the specification when you start writing code…..