C++ for loop is used to repeat statements or a piece of code a specified number of times. It works same as the working of the while loop but it is more flexible than that. That’s why it is the most frequently used loop than the other loops such as while or do-while loops.
Syntax: For loop in c++
For (initialization; condition; increment/decrement)
{
statements;
}
Working: C++ For Loop
- The initialization part executes at once in the complete looping process when control enters the loop.
- After that given condition is evaluated, if the condition is true, control enters the body of for loop and executes its statements.
- Then the increment/ decrement part is executed to change the value of the counter.
- Now, control again moves towards the condition part to evaluate the condition, this process of looping continues till the condition remains true.
- If the condition is false, the loop is terminated and the control moves towards the statements just after the loop.
Flow Chart: For loop in c++
Example:
//for loop in C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i) {
cout << i<<": " << "Hello World"<<endl;
}
return 0;
}
Output
1: Hello World
2: Hello World
3: Hello World
4: Hello World
5: Hello World