Last week a teacher posted an interesting problem. They were looking for an explanation of why to code produced the answer that it did. The code is this:
static void Main(string[] args)
{
int x = 2;
while (x < 12 || (x % 3) != 0)
{
x += 3;
}
Console.WriteLine(x);
}
}
The answer, which takes a while to appear, is 12. But why? It turns out that the value of x overflows. It overflows a lot! Eventually the combination of overflows results in a 12 appearing. It’s not at all obvious how this happens or even why this is not an infinite loop.
There was a lot of discussion of this in the AP CS A Teachers Facebook group. I did find it fascinating and wrote some debugging code to see what was going on.
I have to wonder about the value of showing this code to beginners. Or anyone really. What is the value of the learning, if indeed it does teach anything that beginners are ready to learn. Mostly it is not a great plan, in my opinion at least, to rely on number overflows. Different architectures, especially those with different work lengths, are going to take different numbers of iterations. Are they some that would never get to 12? I’m not sure and I don’t like relying on specific architectures.
BTW on my system with a full word this took 1,431,655,765 overflows. With a short it happens after 21,845 overflows. I still don’t know why it takes so many overflows but I am content for now.
In any case, is there value in asking students to figure out why 12 comes out? I can see people disagreeing on its value as an exercise in debugging. I’m not a fan of it though for a couple of reasons. Firstly, why would you write that code? What is its value? Some people will find it to be an interesting puzzle for the sake of solving a puzzle. I did. But not everyone is “in to” such puzzles. I think most people want to solve a problem to make something work and do something interesting.
I’m also not fond of code that is unclear as to its purpose and goal. In the Facebook group there were a lot of comments from experienced teachers who expected something completely different from the code. Infinite loops being the most common expectation. In fact, that this isn’t an infinite loop is highly unexpected. Code should be written so that someone can figure out what it does without actually executing the code. Especially for beginners.
Now I am not going to be critical of a teacher who does see value in this particular exercise but it’s not for me. As educators we often do create code just for the purpose of highlighting a specific language feature and small, not very useful pieces of code, often make up quiz/test questions for the sake of space and time. But for the most part I believe that students learn better with more context and with code that solves an interesting – to them – problem.
Related posts: