Skip to content

For Loop

There is one other loop that we need to look at: the for loop.

The for loop is another pre-test loop. It is basically a specialised version of the while loop, and is mainly used to repeat a block of code a set number of times. You can think of it like a counting loop, with it counting from a start value to an end value. The for loop has a control variable that stores the number of times the loop has currently run, which the loop uses to see if it should end.

For — when, why, and how

The for loop itself is controlled by three aspects: an initialiser, condition, and post-loop increment.

  • The initialiser appears first in the parenthesis after the for keyword. This is used to set the initial value for the control variable (usually i as we have noted before). If you were using a while loop, this code would appear before the start of the loop.
  • The condition is the expression used to determine if the body of the loop should run. This would be the same as the condition in an equivalent while loop.
  • The post-loop increment updates the control variable. This code runs after the body of the loop. In an equivalent while loop, this would be the increment of the control variable at the end of the body in the while loop.

Any time you have some code that you want to repeat a set number of times, a for loop is most likely what you want to use. It provides you with the mechanics you need to achieve this in a more compact and clear format than a while loop.

In C

The standard format of a for loop is: for (i = 0; i < size; i++) {...}. This can be read in parts as:

  • for i, starting at 0 (the initialiser)
  • while i is less than size, do the body of the loop (the condition)
  • then increment i (using i++) (the post-loop increment)

This will then give you a loop that runs size times.

The example above (for (i = 0; i < size; i++) {...}) assumes that the variable i has already been declared. Many languages, including C#, allow you to declare loop’s control variable within the loop itself, not just initialise it. This is the most common way control variables are created, and neatly packages all of the loop’s data within the loop structure. Using this approach, our previous example would become for (int i = 0; i < size; i++) {...}.

You can tweak all three elements of a for loop. For example, there is no restriction on what value the control variable can be initialised to (assuming it’s a valid value for the variable’s data type). Similarly, the condition of a for loop can be any valid expression. Lastly, the post-loop increment can be any assignment statement. For example, you can count backwards, or in increments of 2.

It is even possible to skip the condition and increment elements of a for loop entirely! This is not done often, but the flexibility can be useful.

How does for work?

Simple for loop

The example we used for the while loop was a counting loop, so it is perfect to transform to a for loop. The looping part of this example is shown below, with comments pointing out the three aspects we need to code into the for loop.

int i = 0; // initialiser
while (i < target) // condition
{
WriteLine(i);
i++; // increment
}

The following code shows the example translated to use a for loop instead of a while loop. Notice that you can match up the initialiser, condition, and increment with the code in the while loop. This will run in the same way as the while loop did, it just brings these three parts together more clearly.

using static System.Console;
using static System.Convert;
int target;
Write("Count to: ");
target = ToInt32(ReadLine());
for(int i = 0; i < target; i++)
{
WriteLine(i);
}

Use the following images to see how this works.

Lines 1-3 prompt the user for input, which is retrieved, converted to an integer, and stored in the variable 'target' on the stack
The for loop begins and as step 4a, the variable 'i' is allocated space on the stack and initialized to 0...
Step 4b performs the comparison which evaluates to true
Line 6 writes the current value of 'i' (0) to the terminal
Step 4c increments the value of 'i' by one, before passing control back to step 4b (the comparison)
Since 1 is less than 10, the comparison evaluates to true, control passes back to line 6
Line 6 writes the current value of 'i' (1) to the terminal
Let's jump ahead to where the number 9 has been printed and i increments to 10
Now the comparison evaluates to false (10 is not less than 10), and the for loop ends
Line 8 prints 'Bye...' to the terminal and the program ends

Reversed for loop

Compare the for loop shown above with that below, which moves in a numerically reverse order.

In this case the post-loop increment element subtracts 1 from the control variable, (incrementing it by a negative number). We have also changed the initialisation to ask for input from the user, rather than being a hard-coded value.

using static System.Console;
using static System.Convert;
int target;
Write("Count down from: ");
target = ToInt32(ReadLine());
for(int i = target; i > 0; i--)
{
WriteLine(i);
}
Lines 1-2 declare an integer variable (max) then prompt the user for input
Lines 3 begins the for loop: The first step (3a) is the initialization: This initialization code reads the user's input ('10'), converts it to an integer, and stores it in the variable max on the stack.
Step 3b is the comparison which evaluates to true
Line 5 writes the value of the variable max (10) to the terminal
Step 3c decrements the value of the variable max by 1 (from 10 to 9), and stores the result back in the same variable
Step 3c decrements the value of the variable max by 1 (from 10 to 9), and stores the result back in the same variable
Line 5 writes the value of the variable max (9) to the terminal
Let's jump ahead to where the number 1 has been printed and max decrements from 1 to 0
This time the comparison at step 3b evaluates to false, and the for loop ends
Line 8 prints 'Blast off !' to the terminal, and the program ends