C++ - For Loop
In C++, the for loop is a control flow statement that allows you to iterate over a sequence of values or perform a block of code a specific number of times. It provides a compact and structured way to write loops with initialization, condition checking, and iteration in a single line. Here's the syntax of the for loop:
for (initialization; condition; iteration) {
// Code to be executed in each iteration
}
The initialization step is executed once before the loop starts and is typically used to initialize a loop control variable. The condition is checked before each iteration, and if it evaluates to true, the code block is executed. After each iteration, the iteration step is performed, which typically updates the loop control variable. The loop continues until the condition becomes false.
for (int i = 1; i <= 5; i++) {
std::cout << "Count: " << i << std::endl;
}
In this example, the for loop initializes the loop control variable i to 1, checks if i is less than or equal to 5, and executes the code block. After each iteration, i is incremented by 1 using the ++ operator.
You can also use the for loop to iterate over a sequence of values, such as an array or a container. Here's an example:
int numbers[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
std::cout << "Number: " << numbers[i] << std::endl;
}
In this example, the for loop iterates over the elements of the numbers array and prints each element.
The for loop provides a convenient and concise way to write loops when the number of iterations or the range of values is known in advance. The loop control variable is scoped to the loop, which means it is only accessible within the loop's code block.