In C++, a for
loop is a control flow statement that allows you to repeatedly execute a block of code for a specific number of times or until a certain condition is met. It has a similar structure to other programming languages.
The syntax of a for
loop in C++ is as follows:
for (initialization; condition; increment/decrement) { // code to be executed }
Let’s break down the different parts of the for
loop:
- Initialization: It is typically used to initialize the loop control variable(s). This part is executed only once before the loop begins.
- Condition: It is an expression that is evaluated before each iteration of the loop. If the condition evaluates to
true
, the loop body is executed. If it evaluates tofalse
, the loop terminates, and the control moves to the next statement after the loop. - Increment/Decrement: It is used to update the loop control variable(s) after each iteration. It can be an increment (
++
) or decrement (--
) operation, but it can also be any other arithmetic or assignment operation. - Code to be executed: This is the block of code that is executed repeatedly as long as the condition is
true
.
Here’s an example that demonstrates a simple for
loop that prints the numbers 1 to 10:
#include <iostream>; int main() { for (int i = 1; i <= 10; i++) { std::cout << i << " "; } return 0; }
Output
1 2 3 4 5 6 7 8 9 10