The for Loop

What’s a loop?

One of the most useful properties of programmable computers is that you can instruct them to repeat a calculation or operation many many times, and they will not (usually) complain. The looping constructs in C allow us to repeatedly execute a block of code many times, without having to manually re-type or re-list the code by hand.

As a simple example, let’s say we want to compute the cumulative sum of integers between 1 and 100. We could write code like the following:

int cumsum = 0;
cumsum = cumsum + 1;
cumsum = cumsum + 2;
cumsum = cumsum + 3;
...
cumsum = cumsum + 100;

As you can see, the above code is not very efficient. As a general rule of programming, any time you find yourself copying and pasting code bits many times over, you should be thinking to yourself, there must be a better way, there must be a way to specify this code more abstractly so that it’s more compact and reusable. Here, we can use a for loop to achieve what we need.

Syntax of a for loop

A generic for loop looks like this:

Press + to interact
for (init_expression; loop_condition; loop_expression) {
// Program statements here
}

The program statements included within the curly brackets { and } is the code block that is to be executed any number of times. This block of code is called the body of the loop. The number of times a loop is iterated depends on the three expressions inside the round brackets that set up the environment for the loop.

  • The init_expression expression is executed once only before the loop starts. It’s typically some initial value assigned to a variable that’s used for controlling the number of iterations of the loop.

  • The loop_condition is an expression that determines whether the loop should continue, or stop depending on whether it evaluates to true or false.

    Note: loop_condition is understood to be false if it evaluates to a zero. Otherwise, it’s considered true.

    Of course, if the condition under which the loop should stop is not specified, it never will and we’ll have an endless loop—our program will never terminate.

  • The loop_expression specifies code that is executed each time through the loop, after the body of the loop is executed.

Example

This is all very abstract, so let’s see a concrete example, by implementing a loop to calculate the cumulative sum of numbers from 1 to 100.

Press + to interact
#include <stdio.h>
int main(void) {
int cumsum = 0;
int i;
for (i = 1; i <= 100; i++) {
cumsum = cumsum + i;
}
printf("The cumulative sum of integers 1 to 100 is %d\n", cumsum);
return 0;
}

Let’s go through the code for the for loop and understand what is happening.

  • On lines 4 and 5, we declare the integer variables cumsum and i, and we initialize the value of cumsum to 0.

  • On line 7, we declare the for loop.

    • The first expression in the round brackets initializes the value of the i variable to 1. This is executed before the loop starts.
    • The next expression is a conditional which evaluates to true if i is less than or equal to 100 and to false otherwise. This expression is evaluated before each iteration of the loop. When this expression is false the loop terminates, otherwise the loop iterates again.
    • Finally the third expression in the round brackets, i++ is executed after each iteration of the loop. In this case, we increment the i variable by one.
  • On line 8, is the code that forms the body of the loop, and is executed on each iteration of the loop. In this case, we add the current value of i (which changes each time through the loop) to the cumsum variable.

  • On line 9, the closing bracket } specifies the end of the body of the loop.

  • On line 11, we print to the screen the value of the cumsum variable.

As you can see, the use of a for loop enables us to write the code for incrementing the cumsum variable just once, and place it inside a loop that’s constructed so that it executes that code 100 times, and each time, uses a different value of i.

Declaring a loop variable

In the previous example, we saw a loop variable i that controls the number of executions of the for loop. In modern C (as specified by C99 and later C standards), we can also declare a loop variable within the for loop construct instead of just initializing it:

for (int i = 0; i <= 100; i++)

But defining a loop variable in the for loop means its scope is restricted to the body of that loop and the variable can't be accessed outside the loop.

Press + to interact
#include <stdio.h>
int main(void) {
int cumsum = 0;
for (int i = 1; i <= 100; i++) {
cumsum = cumsum + i;
}
printf("The cumulative sum of integers 1 to 100 is %d\n", cumsum);
printf("The variable i cannot be accessed outside the for loop: %d\n", i);
return 0;
}

You can remove line 11 to remove the error.

The body of a for loop

If the body of a for loop is a single statement, the curly brackets may be omitted.

Press + to interact
#include <stdio.h>
int main(void) {
int cumsum = 0;
int i = 0;
for (i = 1; i <= 100; i++)
cumsum = cumsum + i;
printf("The cumulative sum of integers 1 to 100 is %d\n", cumsum);
return 0;
}