How a for Loop Works

I received an interesting question the other day. A student asked me to explain a for loop. Dutifully, I set out and gave my description, which he found entirely baffling. So I backed up again and gave this explanation:

A for loop repeats one or more statements a given number of times.

Originally, I spoke about initializing the loop, setting iteration conditions, and of course how to exit. That description was way above his head. He just wanted to know the secret to repeating a chunk of code. That got me thinking.

When I first learned to program, I didn’t know how a for loop worked. All I knew was the where to plug the repeat value:

for(x=0;x<50;x++)

To make a loop repeat 50 times, use the above code. If you need the loop to repeat 4 times, change the 50 to a 4. Oh, and you need to declare x as an int variable earlier in the code. Aside from that, the loop is done: Just ignore all the other characters, symbols, and junk. Ta-da!

Often my desire to teach comes out strong in my explanation. Yet, not everyone who studies C programming wants to learn. They just want to pass the course. That was the case for this student, who really didn’t want to understand the details of a for loop or explore programming concepts. So be it.

More simple loop statements exist. For example, the LOGO language has a repeat keyword. Using C language syntax, it works like this:

repeat(50)
{
    puts("Hello, there!");
}

Sometimes that’s all you need, no fancy anything. Of course, the for keyword offers you a lot of flexibility, and that’s where the C language gets its low-level power. You can do more with a for loop if you need to do more, which is why the C language lacks a repeat keyword.

On a simple level, however, when you need to repeat a chunk of code, or a single statement, you simply use this format:

for(x=0;x<n;x++)

Replace the n with a repeat value, and you’re on your way. You haven’t learned anything about programming, but you’re on your way.