for loop in C++

In this tutorial, we will learn how to execute statements repeatedly using for loop with examples.

There may be a condition in which you need to execute a block of statement multiple times. Executing the same block of statement multiple time is called loop. 

for loop in c++

Syntax of for loop:

for (initialization; test_condition; increment or decrement)
{
       //block of statement to be executed repeatedly
}

Here’s how the above code will work.

The initialization statement is executed only once.  After the initialization the test condition is evaluated. if the expression return true, the block of statement is executed  and the increment or decrements expression is performed. If the test condition return false, for loop is terminated. 

Until the test expression returns true for loop repeats.

Flowchart of for loop

Example of for loop

// Program to calculate the muliplication table of given number upto 10
#include <iostream>
using namespace std;
 
int main () {
    int num, count, mul= 0;
    cout << "Enter a positive integer: ";
    cin >> num;
   // for loop execution
   for(count = 1; count <= 10; ++count)
   {
      mul = num * count;
      cout << num << " * " << count << " = " << mul;
      }
    return 0;
}

Output

Enter a positive integer: 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

The number entered is stored in variable num.

Here the initialization part count = 1 initializes count to 1. Accordance with this count test expression is evaluated. i.e  out test condition becomes

count <= 10  i.e 1<=10  return true

Since above condition is true the block of statement inside the for loop execute and along with the execution the increment expression sets the value of count to 2. And again the test expression is until the condition is true block of code execute. And once the count reach 11 then the test expression 11 <=10 return false which results in termination of for loop.