C++ For Loop

For loop in c++ is used to repeat statements or a piece of code for a specified number of times.  It works similar to the while loop but 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.

Syntax: For loop in c++

For (initialization; condition; increment/decrement)
{
statements;
}

Working: For loop in c++

  1. The initialization part executes at once in the complete looping process when control enters the loop.
  2. After that given condition is evaluated, if the condition is true, control enters the body of for loop and executes its statements.
  3. Then the increment/ decrement part is executed to change the value of the counter.
  4. Now, control again moves towards the condition part to evaluate the condition, this process of looping continues till the condition remains true.
  5. If the condition is false, the loop is terminated and the control moves towards the statements just after the for a loop.

Flow Chart: For loop in c++

Example: For loop

//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

Leave a Reply