C++ for loop

C++ for loop: A C++ for loop can be used to iterate a part of a program structure several numbers of times. If the no.of iterations are fixed then it is highly recommended to use for loop than while and do-while loops. Here, the C++ for loop allows us to perform a number of steps together in a single line. We can also that for loop is an entry controlled loop.



In C++ for loop, the loop variable is used to control the loop. Initially first initialize the loop variable to a value, and then check whether the variable is greater (or) less than the counter value. while evaluating if the loop variable is true, the loop body will be executed and gets updated.

C++ for loop Syntax with Examples

Syntax:

for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}

C++ For Loop

From the above syntax,

Initialization Expression: We have to initialize the loop counter to some value.

Test Expression: We have to test the condition. If the condition is true, it gives output. Otherwise, it will execute the next condition (or) otherwise it will exit the loop.

Increment/ decrement Expression: After executing the loop body so the expression increments/ decrements the loop variable with some value.

C++ for loop Example 1

#include <iostream> 
using namespace std; 
int main() 
{ 
  for (int i = 1; i <= 10; i++) 
   { 
     cout << "Hello freshersnow\n"; 
   } 
return 0; 
} 

Output:

Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow
Hello freshersnow

Example 2:

#include <iostream>
using namespace std;
int main() {
for( int i = 1; i < 10; i++ ) // for loop execution
 {
     cout << "value of i: " << i << endl;
  }
      return 0;
}

Output:

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