Wednesday
Oct222008
C# Pop Quiz
Wednesday, October 22, 2008 at 09:00AM This little exercise comes out of a First Year lecture last week. Given the code:
short i;
for (i = 0; i < 10; i--)
{
Console.WriteLine("i is: " + i);
}
What would it do?
(For those of you that haven't seen it before, the i-- part of the for loop has the effect if reducing the value of i by 1. It is a shorthand version of "i = i - 1")
Rob |
18 Comments |
Reader Comments (18)
I might steal this for my Java students tomorrow ;)
Not sure, just a guess ;)
Dim i As Short = 0
While i < 10
i -= 1
Console.WriteLine("i is: " + i.ToString())
End While
VB knows an overflow and throughs an exception. That seems like a safer thing to do though of course it teaches a whole different principle.
Then all hell breaks loose...
PhilC.
Then all hell breaks loose...
PhilC.
The program as above actually runs as it is written. You don't need to add the ToString, but you can if you like. You can even write:
Console.WriteLine ("Hello".ToString());
...but this might be over doing it a bit.
2^31 == 2,147,483,648 I was pretty close.
The only reason I knew was because of a little game called Hexic, were the maximum score used to be 2^31, since the patch we now have scores in the many trillions.
This given that a match of 3 is 35pts :)
Then again.....
I presume you were referencing your charlamaine, "Always make sure the 'crap' lands on the other persons head".
In the best of cases its an example of making something too terse.
In the worst of cases its a bug.
There is so much other stuff to teach that are more important. I can think of a couple. Knowing the lower bound of a short is not all that important. And in practice you would never write a for loop with that pattern.
and throws an compiler error after that