The for
loop
The for
loop is designed to repeat a set of statements a certain number of times, though it is flexible enough to handle many other looping tasks.
It looks like this:
for (/*init*/ ; /*while-condition*/ ; /*increment*/) { // statements }
Both the init and increment expressions can be empty. The braces are optional if there is only a single statement.
It works like this:
for
statement).For example:
for (int i = 0; i < 3; ++i) { std::cout << "i = " << i << '\n'; }
Does:
i
with the value 0. Note that because this variable was created within the for
statement, it will not be available outside of it.i
is less than 3, and false otherwise.for
statement).i
(adds 1 to whatever value is currently in i
).This will cause the statement "std::cout << "i = " << i << '\n';" to be executed three times, with i
equal to 0, 1, then 2.
After the third time, the value of i
gets incremented to 3, which causes the test i < 3 to return false (3 is not less than 3), and the looping ends (the program continues on with whatever code follows the for
statement).
Generally, to repeat a set of statements N times, you use:
for (int n = /* start-value */ ; n < /* N + start-value */ ; ++n) { // statements }
For example:
#include <iostream> int main() { // Try changing these two values! // Just beware of making N too big! int START_VALUE = 0; int N = 3; for (int i = START_VALUE; i < N + START_VALUE; ++i) { std::cout << "i = " << i << '\n'; } }
Output:
i = 0 i = 1 i = 2
Originally, C++ only had the type of for
loop described above.
C++11 added the "range-based for
loop" for arrays and containers, which looks like:
for (/*variable-declaration*/ : /*container or array*/)