The for Loop

In the last tutorial, we have understood the basic form of loop called the while loop. Now, in this tutorial, we will understand the second type called the for loop.


Syntax and Structure

At first, the syntax of the for loop may look very strange, but it is very easy to write. In fact, this is the easiest form of loop available in C programming. Following is the syntax of the for loop:

for (expr1; expr2; expr3) statement;

It has no more than 3 expressions within parentheses and a single statement after the closing parenthesis. And, we know that the single statement can be replaced by a compound statement to allow multiple statements to execute repeatedly within the same for loop. So, the above syntax can be replaced by the following:

for (expr1; expr2; expr3) {
     // statements to execute repeatedly
}

Decoding the Syntax

Let’s now decode the syntax of the for loop. Usually, in your programming journey, you will encounter the for loops similar to the following:

for(i = 0; i < 10; i++) {
    // do something
}

Let’s understand the above for loop:

  • i = 0:  variable i is initialized to zero. This is called the initialization step. This variable i will be our counter variable
  • i < 10:  the variable i is compared with value 10. If i is less than 10, then the loop body will be executed. 
  • i++:  the variable i is incremented once the body of the loop is executed. 

The above for loop will execute exactly the same way as the following while loop:

i = 0;
while (i < 10) {
    // do something
    i++;
}

The flow of execution of the for loop should be well understood. First, initialization happens and it is done only once. Then, the condition is checked. If the condition satisfies, then the loop body is executed. Here, you need to understand that the increment step (which is the third expression within the parentheses) happens only after the loop body is executed. Then, the condition is again checked and the cycle repeats the same way. 

So, the general structure of the for loop is as follows:

for (initialization; condition; iteration) {
     // Loop body
}

The Flowchart

To further clarify the process of execution of the for loop, observe the following flowchart:

Flowchart of for loop in C

When to use a for loop over while loop?

Generally, for loop and while loop are interchangeable, but there are certain scenarios where one is preferred over the other for better readability and maintainability of the code. 

For loop is generally preferred over while loop when we know exactly how many times the block of code needs to be executed in advance. It’s concise and allows you to initialize the loop variable, check the condition, and increment/decrement the loop variable all in the same line. 

for (int i = 0; i < 10; i++) {
    // Code to execute 10 times
}

On the other hand, while loop is most often used when the number of iterations (how many times you want to execute the loop) is not known in advance. The loop condition is the emphasis here, and it can depend on some external factor – maybe user input. The execution of the while, in this case, can depend upon the user input.

#include <stdio.h>

int main() {
    int n;
    printf("Enter the number (0 to exit): ");
    scanf("%d", &n);
    
    while (n != 0) {
        printf("Enter the number (0 to exit): ");
        scanf("%d", &n);
    }

    printf("You entered zero.");
    return 0;
}

The while loop in the above program will continue to execute until the user enters zero. In these types of scenarios where the number of iterations is not known in advance, the while loop is preferred over the for loop. 


Common Mistakes To Avoid

Some of the most common mistakes beginners while writing for loops are as follows:

Mistake #1:  off-by-one

#include <stdio.h>

int main() {
    for (int i = 1; i < 10; i++) {
    printf("%d ", i);
    }

    return 0;
}

Maybe the requirement is to print numbers from 1 to 10, but the output of the above program is 1 2 3 4 5 6 7 8 9. The number 10 is not displayed because in place of less than or equal to (<=) operator, less than (<) operator is used. 

Mistake #2:  infinite loop

#include <stdio.h>

int main() {
    for (int i = 0; i < 10; i--) {
        printf("%d ", i);
    }

    return 0;
}

The program may seem correct at first, but the problem lies in the iteration statement. Here the use of i- – is incorrect because the loop condition never fails for values less than equal to zero.

Mistake #3:  forgetting to initialize loop variables

If somehow you forget to initialize loop variables, then the behavior will be unexpected. Mostly, you won’t get any output at all. 

Consider the following program: 

#include <stdio.h>

int main() {
    int sum = 0;
    for (int i; i < 5; i++) {
        sum += i;
    }
	return 0;
}

Output: 

No output

Mistake #4:  Not using braces for multi-line statements

#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) 
        printf("%d\n", i);
        printf("something");

    return 0;
}

You may think that “something” will be printed 5 times, but that’s not true. The text “something” will be printed only once as it is not part of the for loop. For multi-line statements, it is crucial to enclose them within the curly braces. 

Mistake #5:  ignoring compiler warnings

Ignoring the compiler warnings can be a big mistake. Compiler almost always try its best to ensure no errors from the programmer. So, make a habit to not ignore compiler warnings. 


Level Up Your Understanding

Question 1:  Can we have any number of expressions in the for loop?

Answer:  we can have at most 3 expressions in the for loop where the first expression is the initialization expression, second is condition checking, and third is iteration. While you can have one initialization and one iteration expression, you can use the comma operator to include multiple expressions in these sections if needed. 

Question 2:  Can’t we have more than one condition in the for loop?

Answer: the for loop in C is designed to have only one condition which decides when the loop will terminate. Although, you can combine multiple conditions using the logical operators

Consider the following example where the two conditions are combined using the logical AND (&&) operator:

#include <stdio.h>

int main() {
    int i, j;
    for (i = 1, j = 10; i < 10 && j > 0; i++, j--) {
        printf("%d %d\n", i, j);
    }
    return 0;
}

Output: 

1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2

Within the for loop, we have separated the two initializations and the iterations with the comma operators. If you want to learn more about how the comma operator works, please click on this link). Also, you can notice the last output, it’s 9 2 and not 10 1. Even the second condition j > 0 is satisfied for j = 1, but the first condition i < 10 is not satisfied for i = 10. As we are using the logical && operator, the compound condition is not satisfied, and hence the output. 

Question 3:  Can we declare the loop variable within the parentheses of the for loop?

Answer:  Absolutely. The C99 standard (and onwards) allow us to declare the loop variables within the for loop. In fact, the for loop in the previous question can be re-written as follows:

#include <stdio.h>

int main() {
    for (int i = 1, j = 10; i < 10 && j > 0; i++, j--) {
        printf("%d %d\n", i, j);
    }
    return 0;
}

The output remains the same. Notice that the variables i and j are now declared within the for loop

Question 4:  Can we use our loop variables outside the for loop if we want? 

Answer:  if the loop variable is declared within the for loop, then it cannot be used outside it. In order to retain the value of the loop variable, you need to declare it outside the for loop.

Question 5:  Can we omit some of the expressions within the for loop?

Answer:  C language gives us the flexibility to omit some or all of the expressions within the for loop. There is a dedicated article on this topic. Please refer to this link.



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.