Cover Image for C++ For Loop
145 views

C++ For Loop

The C++ for loop is a control structure that allows you to execute a block of code repeatedly for a specified number of times or while a certain condition is true. It is one of the most commonly used loop types in C++ and is often used when you know in advance how many times you want to repeat a certain task.

The basic syntax of the for loop is as follows:

C++
for (initialization; condition; update) {
    // Code to be executed in each iteration
}

Here’s a breakdown of each part:

  • initialization: This part is typically used to initialize a loop control variable. It is executed only once at the beginning of the loop.
  • condition: This is a Boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop continues; if it’s false, the loop terminates.
  • update: This part is used to update the loop control variable after each iteration. It is executed after the code block in each iteration.

Here’s an example of a for loop:

C++
#include <iostream>

int main() {
    for (int i = 1; i <= 5; ++i) {
        std::cout << "Iteration " << i << std::endl;
    }

    return 0;
}

Output:

Plaintext
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

In this example, the for loop is used to print “Iteration” followed by the value of i from 1 to 5. The loop control variable i is initialized to 1, the loop continues as long as i is less than or equal to 5, and i is incremented by 1 in each iteration.

You can also use the for loop to iterate over elements of an array or other iterable data structures:

C++
#include <iostream>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};

    for (int i = 0; i < 5; ++i) {
        std::cout << "Element " << i << ": " << numbers[i] << std::endl;
    }

    return 0;
}

Output:

Plaintext
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5

The for loop is versatile and can be used for a wide range of repetitive tasks. It’s important to ensure that the loop control variable is properly initialized, and the loop condition and update expressions are set correctly to avoid infinite loops or incorrect behavior.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS