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: Used to set the initial values of the variables that will control the loop. It is generally 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 is performed to modify the value of the loop control variables. It is typically used to increment or decrement a counter.
  • Instructions to execute: Here, the actions that should 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;
}

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 will display the numbers from 1 to 10 on the screen.

Modifying the Flow of the Loop

Skipping Iterations with continue

The continue statement is used to skip the current iteration and move 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 you to exit the loop before the condition is fulfilled. 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 ended, 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

Generating a Multiplication Table

In this example, we generate a multiplication table for a specific number using a for loop.

#include <iostream>

int main() {
    int number = 5; // Number for which the multiplication table is generated

    for (int i = 1; i <= 10; i++) // Iterates from 1 to 10
    {
        std::cout << number << " x " << i << " = " << number * i << std::endl; // Prints the multiplication of the number by 'i'
    }
    return 0;
}

Iterating Over Arrays

One of the most common applications of the for loop is to iterate over the elements of an array. Here is an example that sums all the elements of an array:

#include <iostream>

int main() {
    int numbers[] = { 1, 2, 3, 4, 5 }; // Declare the array
    int sum = 0; // Variable to store the sum

    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
    {
        sum += numbers[i]; // Add each element of the array to 'sum'
    }

    std::cout << "The sum of the elements is: " << sum << std::endl;
    return 0;
}

Iterating with a Different Step

The value of the update does not always have to be an increment of one. It can be any expression that modifies the control variable. For example, iterating in steps of two:

#include <iostream>

int main() {
    for (int i = 0; i < 10; i += 2) // Increments 'i' by 2 in each iteration
    {
        std::cout << i << std::endl; // Prints the current value of 'i'
    }
    return 0;
}

Decrementing for Loop

The for loop can also be used to iterate in decreasing order:

#include <iostream>

int main() {
    for (int i = 10; i > 0; i--) // Decrements 'i' by 1 in each iteration
    {
        std::cout << i << std::endl; // Prints the current value of 'i'
    }
    return 0;
}

Searching for an Element in an Array

#include <iostream>

int main() {
    int numbers[] = { 1, 2, 3, 4, 5 }; // Declare the array
    int search = 3; // Number to search for
    bool found = false; // Variable to indicate if the number was found

    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
    {
        if (numbers[i] == search) // Compares each element with the searched number
        {
            found = true; // Marks that the number was found
            break; // Exits the loop
        }
    }

    if (found)
    {
        std::cout << "The number " << search << " is found in the array." << std::endl;
    }
    else
    {
        std::cout << "The number " << search << " is not found in the array." << std::endl;
    }
    return 0;
}

These examples are intended to show how to use the FOR loop. It does not mean that it’s the best way to solve the problems they address. Typically, there are better alternatives.