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.

  1. Ben Barden - Blog Tips

    All very well, but what if I want to print a table header for the first row, and format/print the data for every row?

    If I split the first row from the loop, suddenly I have to duplicate the format/print section of the loop.

    I could use a function to reduce the duplication, but is it worth it for code that is only used in one place? What do you think?

    Ben Barden – Blog Tipss last blog post..10 possible answers: Blog types – which are you?

  2. Vincent Tan

    As always, rules sometimes fail in unforeseen manners when edge conditions come in…

    The particular situation you mentioned is one of those. Duplicate the formatting section, or reduce the looping by one iteration?

    That depends on how much work is done for each of the options. Choose the one which has less.

    Not only am I quite free with my loop limits, I’m also quite free with breaking rules when required. 🙂

Comments are closed.