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:
int arr[5] = {1, 2, 3, 4, 5};
: This line declares and initializes an integer array namedarr
with a size of 5. The values 1, 2, 3, 4, and 5 are assigned to the array elements.for (int i = 0; i < 5; i++) {
: This line starts the for loop. It initializes a variablei
with a value of 0, which acts as the loop counter. The conditioni < 5
specifies the loop will continue executing as long asi
is less than 5. Thei++
statement increments the value ofi
by 1 after each iteration.cout << arr[i] << " ";
: This line prints the value of thei
th element of the arrayarr
using thecout
statement. The<<
operator is used to concatenate the array element with a space character.}
: 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
.