Easy Tutorial
❮ Cpp Sizeof Operator Cpp Modifier Types ❯

C++ for Loop

C++ Loops

The for loop allows you to write a repetitive control structure that executes a specific number of times.

Syntax

The syntax for the for loop in C++:

for ( init; condition; increment )
{
   statement(s);
}

Here is the control flow of the for loop:

Flowchart

Example

#include <iostream>
using namespace std;

int main ()
{
   // for loop execution
   for( int a = 10; a < 20; a = a + 1 )
   {
       cout << "Value of a: " << a << endl;
   }

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19

Range-based for Loop (C++11)

The for statement allows simple range iteration:

int my_array[5] = {1, 2, 3, 4, 5};
// Each array element multiplied by 2
for (int &x : my_array)
{
    x *= 2;
    cout << x << endl;  
}
// auto type is also a feature of C++11, used to automatically get the type of the variable
for (auto &x : my_array) {
    x *= 2;
    cout << x << endl;  
}

The first part of the for statement defines the variable used for range iteration, similar to the variable declared in a regular for loop, with its scope limited to the loop. The second part after the ":" represents the range to be iterated over.

Example

#include<iostream>  
#include<string>  
#include<cctype>  
using namespace std;  

int main()  
{  
    string str("some string");  
    // range for statement  
    for(auto &c : str)  
    {  
        c = toupper(c);  
    }  
    cout << str << endl;  
    return 0;  
}

The above program uses a range for statement to iterate over a string and convert all characters to uppercase, resulting in the output:

SOME STRING

C++ Loops

❮ Cpp Sizeof Operator Cpp Modifier Types ❯