Recently I was posed the following question:

Write a piece of code that prints all odd integer numbers between 1 and 99

This really isn’t a difficult question but it still requires some thought. When I’m posed with any question I like to break things down into their constituent parts.

Here’s the process I went through:

Okay, so I’ll define two variables for a start and end value and there’s going to have to be a loop.

int startValue = 1;
int endValue = 99;
for(int i = startValue;
     i <= endValue;
     i++)
{
   // work out if "i" is an odd number
}

Now, for the odd number detection. And… after a few umms and errrs … I’m going to have to mod 2 (%2) the current value of i to work out if the value is odd. More … umms and errs. Okay, I’ve finally worked out that if something mod 2 is not equal to 0 it’s clearly an odd number. This took me longer than it should have but never mind. Once I’ve detected if i is an odd number I’ll then put the odd number into a list for use later.

int startValue = 1;
int endValue = 99;
IList<int> oddValues = new List&lt;int&gt;();
for(int i = startValue;
     i &lt;= endValue;
     i++)
{
   if(i%2 != 0)
   {
      oddValues.Add(i);
   }
}

Those of you that are good at these little puzzles, or just think this is way too easy, might already be screaming at me about one of the following:

  • Why are you using a IList, why don’t you just print the value?
  • Odd numbers are always 2 apart so why aren’t you just increment i by 2 using i+=2?

(More …)