C++ for loop

In C++, the for loop is a control structure that allows a block of code to be executed repeatedly for a fixed number of times. The syntax of the for loop is as follows:

refe‮i:ot r‬giftidea.com
for (initialization; condition; update) {
    // Code to execute for each iteration
}

The initialization statement is executed once at the beginning of the loop and is used to initialize a loop variable. The condition statement is checked before each iteration of the loop and is used to determine if the loop should continue or exit. The update statement is executed after each iteration of the loop and is used to update the loop variable.

Here's an example of a for loop:

for (int i = 0; i < 5; i++) {
    cout << i << endl;
}

In this example, the loop initializes the variable i to 0, checks if i < 5, executes the code block (cout << i << endl;), and then increments i by 1. This process is repeated until i >= 5, at which point the loop exits.

The for loop is useful when you know exactly how many times you need to execute a block of code. If you don't know how many times the loop will execute, you may want to use a while or do-while loop instead.

You can also use a for loop to iterate over the elements of an array or container, like this:

int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
    cout << arr[i] << endl;
}

In this example, the loop iterates over the elements of the array arr, printing each element to the console.