Language: EN

cpp-bucle-for

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

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.

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
}
  • Initialization: It is used to set the initial values of the variables that will control the loop. Typically, it is used to initialize a counter.
  • Condition: It is a boolean expression that is evaluated before each iteration. If the condition is true, the loop continues executing; if false, it exits the loop.
  • Update: An action is performed to modify the value of the loop control variables. It is generally 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 the numbers from 1 to 10:

#include <iostream>

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

In this example:

  • The initialization int i = 1 sets the initial value of i to 1.
  • The condition i <= 10 ensures that the loop runs 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 the numbers from 1 to 10 will be displayed on the screen.

Modifying the Flow of the Loop

Skipping Iterations with continue

The continue statement is used to skip the current iteration and jump 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;
}

Exiting 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 there is no need to continue iterating.

#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;
}

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;
}

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

Multiple Declarations

In the initialization and update sections, multiple declarations can be included 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;
}

Practical Examples

These examples aim to show how to use the FOR loop. It does not mean that it is the best way to solve the problems they address. There are usually better alternatives.