The for loop has a more efficient loop structure and is an entry-control loop. The loop allows the programmer to write the execution steps together in a single line and also the specific number of times the execution is to be iterated.
for loop Flowchart:

It has three computing steps as shown in the syntax below.
- initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(
;
). - condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(
;
). - Increment or Decrement: The third one is the increment or decrement of the variable for the next iteration. Here, we do not need to use the semicolon at the end.
The syntax for for loop
in C++:
1 2 3 4 | for(initialization; condition; Increment or Decrement) { // Statements } |
You should use for a loop when the number of iterations is known beforehand, i.e. when the number of times the loop body is needed to be executed is known.
Example of C++ for loop
1 2 3 4 5 6 7 8 9 10 11 12 | #include <iostream> using namespace std; int main () { // for loop execution for( int i = 1; i <= 10; i++ ) cout << "value of i: " << i << endl; return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 | value of i: 1 value of i: 2 value of i: 3 value of i: 4 value of i: 5 value of i: 6 value of i: 7 value of i: 8 value of i: 9 value of i: 10 |