cpp-bucle-for

What is and how to use the FOR loop in C++

  • 6 min

A for loop in C++ is a control structure that allows executing a block of code a specific number of times. It is one of the most commonly used control structures.

If you want to learn more, check out the Introduction to Programming Course

Basic Syntax

The syntax of a for loop in C++ consists of three main parts: initialization, condition, and update.

These parts are specified within the parentheses of the for loop and are separated by semicolons.

for (initialization; condition; update)
{
    // Instructions to execute in each iteration
}
Copied!
  • Initialization: Used to set the initial values of the variables that will control the loop. Typically, it’s used to initialize a counter.
  • Condition: A boolean expression that is evaluated before each iteration. If the condition is true, the loop continues executing; if false, the loop exits.
  • Update: An action performed to modify the value of the loop control variables. Usually used to increment or decrement a counter.
  • Instructions to execute: Here, the actions to be performed in each iteration of the loop are specified.

Basic Example

Let’s look at a simple example where we use a for loop to print numbers from 1 to 10:

#include <iostream>

int main() {
    for (int i = 1; i <= 10; i++)
    {
        std::cout << i << std::endl;
    }
    return 0;
}
Copied!

In this example:

  • The initialization int i = 1 sets the initial value of i to 1.
  • The condition i <= 10 ensures the loop executes while i is less than or equal to 10.
  • The update i++ increments i by 1 after each iteration.
  • Inside the loop, we use std::cout to print the current value of i to the console.

The result is that numbers from 1 to 10 will be displayed on the screen.

Modifying Loop Flow

Skipping Iterations with continue

The continue statement is used to skip the current iteration and proceed directly to the next iteration of the loop.

#include <iostream>

int main() {
    for (int i = 0; i < 10; i++)
    {
        if (i % 2 == 0)
        {
            continue; // Skip even numbers
        }
        std::cout << i << std::endl;
    }
    return 0;
}
Copied!

Breaking the Loop with break

The break statement allows exiting the loop before the condition is met. This is useful when a specific value is found and further iteration is unnecessary.

#include <iostream>

int main() {
    for (int i = 0; i < 10; i++)
    {
        if (i == 5)
        {
            break; // Exit the loop when i is 5
        }
        std::cout << i << std::endl;
    }
    return 0;
}
Copied!

Special Cases

Using External Variables

It is possible to use a variable declared outside the for loop as the control variable. This can lead to confusion if not handled properly:

#include <iostream>

int main() {
    int i = 0;
    for (i = 0; i < 5; i++)
    {
        std::cout << i << std::endl;
    }
    std::cout << "Value of i after the loop: " << i << std::endl;
    return 0;
}
Copied!

In this case, i retains its value after the loop has finished, which will be 5.

Multiple Declarations

In the initialization and update sections, you can include multiple statements separated by commas. This is useful when multiple control variables are needed:

#include <iostream>

int main() {
    for (int i = 0, j = 10; i < j; i++, j--)
    {
        std::cout << "i: " << i << ", j: " << j << std::endl;
    }
    return 0;
}
Copied!

Practical Examples

These examples are intended to show how to use the FOR loop. This does not mean it’s the best way to solve the problem they address. Usually, there are better alternatives.