You can start in the middle of a loop

I’ve always been quite free with the limits of my loops. When I first learned the do-while, for and while loops, the start and end points weren’t fixated in my mind. Let me explain.

The usual start and end points are 0 and the number of iterations required minus one (yes, I’m in zero-index C territory). The professor was very persistent in ensuring we know how many iterations there were (I was a freshman in university). I thought it’s obvious, but apparently it’s a common error to miscount.

Just as important, you shouldn’t be fixated on the number of iterations in a loop too. Say you need to iterate for each month in a year. That’s 12 iterations. For the first 8 months, you need to do one thing, and for the other 4 months, you need to do something else. This is not recommended:

int i = 0;
for (i=1; i<=12; ++i)
{
	if (i<=8)
	{
		// do A
	}
	else
	{
		// do B
	}
}

It's confusing to read if tasks A and B are complex. Better to just:

int i = 0;
for (i=1; i<=8; ++i)
{
	// do A
}

for (i=9; i<=12; ++i)
{
	// do B
}

The tasks are now clearly defined and the code is easier to read. With the current hardware, I think the absence of 1 if-else or the presence of a 2nd for loop won't make much of a speed issue, so it's not really for optimisation purposes either.

Another common code chunk I encounter is the do-the-first-one-differently loop. There's a list you need to iterate through, but for the first one, you have to do something extra or different.

Here's an idea. Why don't you do that first iteration by itself, and start the loop on the second iteration?

There is no restriction you have to start a loop with the first or last item, or with 0 or (list.Count - 1). Loop where it makes sense. I hereby give thee permission to start in the middle of a loop.

Beginning C# – Arrays and iterations

Numbered mailboxes @iStockphoto / Eliza Snow So you’ve learnt a bit about variables such as ints and floats. What happens if you need, say a bunch of integer variables with similar purposes? For example, ten decimal variables to store prices. This is where arrays come in.

One and two dimensional arraysArrays offer a simple syntax to declare a series of variables of the same type with minimum work. Think of arrays as boxes in sequential order, where the boxes can only hold a certain type of item.

When someone uses the term “array”, the person usually means a one-dimensional array. What’s the difference? Imagine you have a series of boxes. That’s a one-dimensional array. Then imagine each of those boxes is the start of another series of boxes. That’s a two-dimensional array. You can even go on to three-dimensional arrays, where you stack two-dimensional arrays on top of each other.

Alright then, how do you use them? Here comes the source code.

            const int numberofelements = 10;
            double[] multiplesofpi = new double[numberofelements];
            int i;

            for (i = 0; i < numberofelements; ++i)
            {
                // The result of an operation between two numbers has
                // the precision of the number with the higher precision.
                // Math.PI is a double, which has a higher precision than
                // i, an integer. So the result of i * Math.PI is a
                // double.
                multiplesofpi[i] = i * Math.PI;
            }

            // reverse the for loop
            for (i = numberofelements - 1; i >= 0; ----i)
            {
                Console.WriteLine("Box {0} has {1}", i, multiplesofpi[i]);
            }

            Console.WriteLine("End of program");
            Console.ReadLine();

So we declare an array of doubles named multiplesofpi. Note the square brackets after the double. This line

            double[] multiplesofpi = new double[numberofelements];

just tells the compiler that we want an array of doubles. The new keyword simply tells the compiler to create a new array of doubles, with “numberofelements” number of doubles bunched together. Remember the const keyword we learnt?

            for (i = 0; i < numberofelements; ++i)
            {
                // The result of an operation between two numbers has
                // the precision of the number with the higher precision.
                // Math.PI is a double, which has a higher precision than
                // i, an integer. So the result of i * Math.PI is a
                // double.
                multiplesofpi[i] = i * Math.PI;
            }

In the for loop, we assign each element of the array with a value. Each array element can be accessed using an index, which in our case is the variable i.

There are 10 iterations in this case. An iteration refers to an instance of something being done repetitively, such as in a for loop, or while loop. In each iteration, we multiply the number of the iteration by the value of PI, which is about 3.14159. The Math library provided by .NET already contains the constant value of PI, so we’ll just use that.

It takes some getting used to, but computers really like counting from zero. We humans start counting from 1, and for a long time, cannot grasp the idea of nothingness. Computers however, have no problems with zero. Maybe they’re more advanced than us humans…

Anyway, we then practise reversing the for loop with

            // reverse the for loop
            for (i = numberofelements - 1; i >= 0; ----i)
            {
                Console.WriteLine("Box {0} has {1}", i, multiplesofpi[i]);
            }

This is important, because there will come a time in your programming life where going backwards and forwards in a sequential manner is critical. Besides, it trains your mind to think differently, and that’s great by itself.

Homework
Write the first for loop in reverse manner. Then try writing the second for loop in forward manner. Convince yourself that the array will contain the same values, regardless of whether the for loop is in forward manner or reverse manner.

Download the source code.