C++ For Loop

In while and do…while loops we need to write the increment or decrement operation to break the loop after sometime. But in for loop we have an option of incrementing or decrementing outside the loop body. Also for loops have an option of initializing the variable. Thus no need to write any incrementing/decrementing step inside the loop body like we do in while and do…while loops. For loop looks like below.

Syntax of For Loop

for (initialization; termination; increment-decrement) 
    statement

OR

for (initialization; termination; increment-decrement) 
{
    statement(s)
}

Initialization: As the loop starts initialization expression is executed once. This expression initializes the loop.

Termination: The loop terminates if the value of termination expression equal to false.

Increment-Decrement: With each iteration this expression is executed. This expression can increment or decrement the value.

For loop examples

Try It

#include <iostream> 
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
	cout << "i is " << i << endl; 
return 0;
}

Here int i = 0 is initialization
i < 5 is Termination Condition
i++ is Changing value of variable by incrementing it by 1
cout << " i is " << i << endl; will be executes till i will become 5

Output of above code will be

i is 0
i is 1
i is 2
i is 3
i is 4

For Loop without Initialization, Termination and Increment-Decrement

Initialization, Termination and Increment-Decrement expressions are optional. It is possible to have a for loop as shown below.

for (;;) 
{
    statement(s)
}

Above loop will run forever and is equivalent to

while (true) 
{
    statement(s)
}

We can also write a for loop without Initialization and Increment-Decrement expressions as shown below

int i = 0;
for ( ; i < 10; )
{
    cout << i << " ";
    i++;
}

Output of above code will be

0  1  2  3  4  5  6  7  8  9

We can also write a for loop using only the Increment-Decrement expression as shown below

int i = 0;
for ( ; ; i++)
{
    cout << i << " ";  
    if(i==10)
        break;
}

Output of above code will be

0  1  2  3  4  5  6  7  8  9  10

Null Statements

It is possible to have a for loop without statement/s as shown below. In this the for loop will perform the Initialization, checking Termination condition and increment/decrement operation and then will exit the loop.

for(int i=0; i < 10; i++);

Above loop will run 10 times and will terminate after that. Before termination the value of i will be 10

Advanced details about For loop

Initialization: This is a single expression which may include multiple variable declaration of same type. If you want to declare 2 variables then you should write with comma seperated like int i=0, j=0 but not with semicolon seperated like int i=0; int j=0. Also you can not write like int i=0, float j=0.

Termination: Here you can write multiple terminating conditions but only the last one will be valid and previous ones will get ignored. For example b > 5, a < 10 here b > 5 will be ignored and only a < 10 will be a valid terminating condition.

Increment-Decrement: Here also you can write multiple increment-decrement operations seperated by ,.

Below is the code implementing above features

int main ()
{   
   for( int a = 1, b = 10, c = 1 ; a < 10; a = a + 1, b = b - 1, c = c * 2 )
   {
       cout << "value of a: " << a << endl;
       cout << "value of b: " << b << endl;
       cout << "value of c: " << c << endl;
   } 
   return 0;
}

Output of above code is shown below

value of a: 1
value of b: 10
value of c: 1
value of a: 2
value of b: 9
value of c: 2
value of a: 3
value of b: 8
value of c: 4
value of a: 4
value of b: 7
value of c: 8
value of a: 5
value of b: 6
value of c: 16
value of a: 6
value of b: 5
value of c: 32
value of a: 7
value of b: 4
value of c: 64
value of a: 8
value of b: 3
value of c: 128
value of a: 9
value of b: 2
value of c: 256

Above we mentioned that in initialization expression we can define multiple variables only of same type. Below we will mention a way to initialize different type variables.

for(struct { int a; float b; } s = { 0, 0.5 } ; s.a < 5 ; ++s.a, ++s.b) 
{
	cout <<"a="<< s.a << " b=" << s.b << endl;
}

Below will be the output of above code

a=0 b=0.5
a=1 b=1.5
a=2 b=2.5
a=3 b=3.5
a=4 b=4.5

Sequence of execution in for loop is shown in below steps

Step1: Perform Initialization
Step2: Check Terminating Condition. If it is false go to Step6
Step3: Execute Statements
Step4: Increment-Decrement Variable
Step6: Go to Step2
Step7: Stop

Below is the flow chart of for loop

For Loop


Range-Based For Loop

The new standard introduced a range based for loop which is simpler and can be used to itearte through the collection of elements. It can be represented in the following way

for ( range_declaration : range_expression ) statement;

range_expression must represent a sequence of objects having begin and end members like in list , array , vector , string , etc.

That means we can use all iterators like list , array , vector , string , etc in range_expression.

range_declaration defines a variable and each element coming from range_expression will be converted to this variable’s type. For example if range_declaration is char type and range_expression is string type then each element will be converted to char type and will be assigned to the variable as shown below.

Each element coming from “szName” will be converted to char type and then assigned to the variable “ch”.

int main ()
{
    string szName = "TutorialCup";
    for(char ch : szName)
    {
        cout << ch << endl;
    }

    return 0;
}

Output of above code is shown below

T
u
t
o
r
i
a
l
C
u
p

More example of a range based for loop

int main() 
{
    string szName = "TutorialCup";
    for (const char &ch : szName) // access by const reference
        cout << ch << ' ';
    cout << '\n';
    
    for (auto ch : szName) // access by value, the type of ch is ch
        cout << ch << ' ';
    cout << '\n';
 
    for (auto&& ch : szName) // access by reference, the type of ch is char&
        cout << ch << ' ';
    cout << '\n';
 
    for(char ch : {'T','u','t','o','r','i','a','l','C','u','p'}) // the initializer may be a braced-init-list
        cout << ch << ' ';
    cout << '\n';
}

Below is the output from above code

T  u  t  o  r  i  a  l  C  u  p
T  u  t  o  r  i  a  l  C  u  p
T  u  t  o  r  i  a  l  C  u  p
T  u  t  o  r  i  a  l  C  u  p

Terminating Range-Based For Loop

A range-based for loop terminates by executing break , return and goto statement inside the body of a range-based loop. A continue statement only terminates the current iteration of a loop.

Important points about range-based For loop

  1. Arrays will be automatically recognized by a range-based for loop.
  2. Range-based for loop can recognize containers having .begin() and .end().
  3. For anything else, range-based for loop uses argument-dependent lookup begin() and end().
Translate »