C++ for Loop
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:
init is executed first and only once. This step allows you to declare and initialize any loop control variables. You can also leave this empty, as long as there is a semicolon.
Next, the condition is evaluated. If it is true, the loop body is executed. If it is false, the loop body is not executed, and control flow jumps to the statement following the for loop.
After executing the loop body, control flow jumps back to the increment statement. This statement allows you to update the loop control variables. This statement can also be left empty, as long as there is a semicolon after the condition.
The condition is evaluated again. If it is true, the loop is executed, and this process repeats (loop body, then increment, then re-evaluate the condition). When the condition becomes false, the for loop terminates.
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