C++ for Loop
forLoops allow you to write a repeating control structure that executes a loop a specific number of times.
Syntax
In C++forSyntax of the loop:
for ( init; condition; increment )
{
statement(s);
}
The following is the control flow of the for loop:
- initIt is executed first, and only once. This step allows you to declare and initialize any loop control variables. You may also write no statement here, as long as a semicolon appears.
- Next, it will determineconditionIf true, the loop body is executed. If false, the loop body is not executed, and control flow jumps to the next statement immediately following the for loop.
- After the for loop body has been executed, control flow jumps back to the aboveincrementstatement. This statement allows you to update the loop control variable. This statement can be left empty, as long as a semicolon appears after the condition.
- The condition is evaluated again. If true, the loop is executed, and this process repeats continuously (loop body, then increment step value, then re-evaluate condition). When the condition becomes false, the for loop terminates.
Flowchart
Example
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 results:
a 的值: 10 a 的值: 11 a 的值: 12 a 的值: 13 a 的值: 14 a 的值: 15 a 的值: 16 a 的值: 17 a 的值: 18 a 的值: 19
Range-based for loop (C++11)
The for statement allows simple range iteration:
int my_array[5] = {1, 2, 3, 4, 5};
// multiply each array element by 2
for (int &x : my_array)
{
x *= 2;
cout << x << endl;
}
// auto type is also from the C++11 new standard, used to automatically get the variable's type
for (auto &x : my_array) {
x *= 2;
cout << x << endl;
}
The first part of the for statement above defines the variable used for range iteration, just like a variable declared in a normal for loop, whose scope is limited only to the loop's range. The second block after ":" represents the range to be iterated.
Example
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main()
{
string str("some string");
// range-based for statement
for(auto &c : str)
{
c = toupper(c);
}
cout << str << endl;
return 0;
}
The above program uses a Range for statement to traverse a string, converts all characters to uppercase, and outputs the result as:
SOME STRINGother extensions