FOR Beginners: The For Loop in C

for loop cThe For Loop is a basic technique in C programming, and has remained largely unchanged in the languages based on or inspired by C, such as C++, Java, Objective-C, C#, D, and JavaScript. Its main purpose is to repeat a section of code a predefined number of times. However, as you will see, there are a few other ways that the For Loop can be used, and this includes infinite loops and dynamically changing the number of times that the loop is executed.

Beginners to C programming should consider looking at a more comprehensive guide to the language, which would include more information about declaring variables, unary operations, and program structure. Learning C Programming covers all of these, and a lot more. Complete beginners – those who have not gone as far as choosing a C compiler – might prefer C Programming for Beginners, which also includes useful information about the compilers available for Windows and Mac.

A simple For Loop looks like this:

int count;

for (count=0; count < 10; count++) {
// runs all of the code between the { and }
// 10 times.
}

The code that is executed each time the loop is run is placed within curly brackets, although an exception can be made if the code to be run is only a single line.

for (count=0; count < 10; count++)
printf("Run...\n");

The conditions for the loop are placed in parenthesis after the keyword for, these conditions break down into three parts separated by semicolons.

The first part is the initialization, and this sets the starting condition for the loop. Often this is used to set an integer variable (sometimes thought of as a counter) to a number. ANSI C is a standard version of the C language and, originally, all variables had to be declared at the start of the block/function. C99 and later versions allow you to declare variables almost anywhere, and so you can create a new variable for use just within the For Loop if it would be useful to you.

for (int count=0; count < 10; count++) {
// runs all of the code between the { and }
// 10 times.
}

The second part of the For Loop’s conditions, is an expression that describes what needs to be true for the loop to keep running. In this example, the variable count must be less than 10.

The final part is a statement that is run at the end of every iteration – before the loop restarts – and is usually, as in this case, used to increment the variable named in the initialization part.

Counting Up

The most common use of a For Loop is to count up from the starting value to a predefined end value, and execute a block of code each time.

You will generally use this structure when processing arrays, the first entry of which is at position 0. So to start on that the first element, the loop should also start at 0, but if you wanted this code to run 10 times then the evaluation condition must be set to “less than 10”. Since 0–10 is eleven steps, in contrast to 1–10 which is ten steps.

The unary operator ++ is used to increment the count after every iteration of the loop. This is equivalent to saying count = count + 1.

for (count=1; count <= 10; count=count+1) {
// runs all of the code between the { and }
// 10 times.
}

Remember that the condition is checked at the start of every iteration, including the first time the loop is run. In the following example, the code inside the For Loop won’t run at all, since the starting initialization already makes the expression in the condition “false”. count is never less than 10.

for (count=11; count <= 10; count=count+1) {
// this code is never run.
}

Counting Down

The For Loop is not limited to counting up from one number to another, it can also count backwards from the starting value. You will often see this use the unary operator — to decrement the counter after every iteration of the loop.

for (count=10; count > 0; count--) {
// runs all of the code between the { and }
// 10 times, starting at 10 and working down to 1.
}

Infinite Loops

Generally speaking, an infinite loop is a bad thing: your program will never end… unless it crashes. But there are sometimes legitimate reasons for not wanting a loop to end, and the For Loop can also be used in this way.

An infinite loop can be written in C as follows:

for (;;) {
// runs all of the code between the { and }
// forever.
}

It would be unusual to need a truly infinite loop, since most loops need to terminate eventually. However, it is often useful to create a loop which will not terminate until a particularly complicated condition is met, or you might have many conditions that could cause the loop to exit. In these cases, your source code may be easier to read if you check the conditions during the code block and then exit the loop when necessary. Breaking out of an infinite loop (or any other loop for that matter) can be done with the, usefully named, break statement.

Break and Continue

Break is used to exit a loop early, or exit an infinite loop that would otherwise run forever. It is usually run after an if statement, after checking whether a certain condition has been reached.

The following code example actually performs the same function as the first example in the section “Counting Up” above.

int count = 1;
for (;;) {
// runs all of the code between the { and }
// 10 times.
count++;
if (count > 10)
break;
}

On occasion, you may want to skip all of the code in a For Loop and continue at the next iteration. The continue statement does exactly that. In the following example, the printf() call is never executed.

for (count=1; count <= 10; count++) {
continue;
printf("C: %u\n", count);
}

Continue does not exit the loop; if you print the value of count after the For Loop is complete, you will see that it does still reach 11.

Controlling the Iterations

As shown earlier, a For Loop commonly uses the unary operations, ++ and –, to increment or decrement a counter variable. However, other statement types can also be used here.

count++ is the equivalent of count = count + 1, so it makes sense that count = count + 2 can be used in a For…Loop, to jump up in increments of two. count = count + 10 can be used to jump up in increments of 10, and obviously any assignment statement along these lines will also work.

for (count=1; count <= 10; count=count+2) {
// runs all of the code between the { and }
// 5 times because count moves in increments of 2.
}

Another way to exit a loop is to change the variables used in the For Loop’s declaration, while the program is running. For example, the following code exits the loop in a slightly different way from break. Instead of terminating the loop immediately, the rest of the code between the curly brackets is run. However, on the next evaluation of the loop’s condition, count is too high and the loop terminates. This code actually outputs: 1, 2, 3, 4, 11, and then stops.

for (count=1; count <= 10; count++) {
if (count == 5)
count = 11;
printf("C: %u\n", count);
}

If the loop’s condition refers to a variable instead of a fixed number then this value can also be changed. Adjusting the condition is another way to change how many times the loop runs.

int count = 1;
int limit = 10;

for (count=1; count <= limit; count++) {
// runs all of the code between the { and }
// 15 times.
if (count == 10)
limit = 15;
}

The following example is an infinite loop that counts up to 10, then back down to 1, then up to 10 again, and so on… It does this by changing the value that is added to count.

int count = 1;
int limit = 10;
int ivalue = 1;

for (count=1; count <= limit; count=count+ivalue) {
// runs all of the code between the { and }
// infinitely, counting forwards and backwards
// between 1 and 10.
if (count == 10)
ivalue = -1;
else if (count == 1)
ivalue = 1;
}

You can get quite creative with For Loops, but you should always aim to make your code as clear and as easy to understand as possible. For example, would using pointers or function calls in a For Loop’s declaration be worth the confusion it could cause?

Further Reading

The For Loop is one of three basic loop types in C; the others are the While Loop and Do…While Loop. C Basic Programming for Beginners provides guidance and examples of programming in C – including the other two loop constructs not covered here.