C++ for loop
In the previous chapter we have already seen the while loop in C++ programming language.
Table of content
C++ for loop :
The for-loop is also used to execute some statements repetitively for a fixed number of times. Syntax of the for loop is as follow -
for ( init; condition; increment ) { statement(s); }
Example of for loop :
#include <iostream> using namespace std; int main () { // for loop execution for(int i = 0; i < 10; i = i + 1 ) { cout << "value of i : " << i << endl; } return 0; }
Output :
value of i : 0 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
Explanation of the program :
For loop comrpise of the three steps.
- In first step, the initial expression is evaluated. Initial value is provided to the loop index variable.
- In next step, the test-expression is evaluated. If the value is non-zero, the loop is executed and if the value is zero, the loop is terminated without execution.
- In the third step of the execution of for-loop, the update expression is evaluated.
C++ For loop flowchart :
Different ways of the for loop are also explained in our C section
C++ infinite for loop :
#include <iostream> using namespace std; int main () { for(;;) { cout << "Hello World !"; } return 0; }