for loop with array c++

The for loop in C++ is a control structure that allows us to execute a block of code repeatedly. It is commonly used with arrays to iterate over each element and perform certain operations.

Here is an example of a for loop with an array in C++:

int arr[5] = {1, 2, 3, 4, 5};

for (int i = 0; i < 5; i++) {
    // Code to be executed for each iteration
    cout << arr[i] << " ";
}

Explanation of each step:

  1. int arr[5] = {1, 2, 3, 4, 5};: This line declares and initializes an integer array named arr with a size of 5. The values 1, 2, 3, 4, and 5 are assigned to the array elements.

  2. for (int i = 0; i < 5; i++) {: This line starts the for loop. It initializes a variable i with a value of 0, which acts as the loop counter. The condition i < 5 specifies the loop will continue executing as long as i is less than 5. The i++ statement increments the value of i by 1 after each iteration.

  3. cout << arr[i] << " ";: This line prints the value of the ith element of the array arr using the cout statement. The << operator is used to concatenate the array element with a space character.

  4. }: This closing curly brace marks the end of the for loop block.

The for loop will iterate over each element of the array arr and print its value on the console. In this example, it will print: 1 2 3 4 5.