The C++ for loop is a loop statement that allows you to execute a block of code repeatedly for a specified number of times. It is commonly used to iterate over arrays and other data structures.
Here’s the basic syntax of a for loop in C++:
for (initialization; condition; increment) {
// code to be executed repeatedly
}
Let’s break down each part of the syntax:
- The
initializationsection is executed only once at the beginning of the loop. It usually declares and initializes a loop counter variable. - The
conditionsection is checked at the beginning of each iteration. If it is true, the loop body is executed. If it is false, the loop terminates. - The
incrementsection is executed at the end of each iteration. It usually increments the loop counter variable.
Here’s an example of a for loop that prints the numbers from 1 to 5:
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}
In this example, the loop counter variable i is initialized to 1, and the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented by 1.
The output of this program would be:
1 2 3 4 5
You can also use a for loop to iterate over an array. Here’s an example that prints the elements of an array:
int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << endl;
}
In this example, the loop counter variable i is used to access each element of the array arr using the index i. The loop continues as long as i is less than the length of the array (which is 5 in this case).
The output of this program would be:
1 2 3 4 5