for loop
suggest changeA for loop executes statements in the loop body, while the loop condition is true. Before the loop initialization statement is executed exactly once. After each cycle, the iteration execution part is executed.
A for loop is defined as follows:
for (/*initialization statement*/; /*condition*/; /*iteration execution*/)
{
// body of the loop
}
Explanation of the placeholder statements:
initialization statement: This statement gets executed only once, at the beginning of theforloop. You can enter a declaration of multiple variables of one type, such asint i = 0, a = 2, b = 3. These variables are only valid in the scope of the loop. Variables defined before the loop with the same name are hidden during execution of the loop.condition: This expression is evaluated before each execution of the loop body, and the loop ends if it is contextually converted tofalse. An omitted condition is treated astrue.iteration execution: This expression is evaluated after the loop body and before the next condition check, unless theforloop is left bybreak,goto,return, or an exception.continuedoes not skip it. Several expressions can be sequenced with the comma operator, as ina++, b+=10, c=b+a.
The standard describes a for loop as equivalent to this while loop, except that a continue in the for body still evaluates the iteration expression before testing the condition again:
{
/*initialization*/
while (/*condition*/)
{
/*body of the loop*/
/*iteration execution*/
}
}
The most common case for using a for loop is to execute statements a specific number of times. For example, consider the following:
for (int i = 0; i < 10; i++) {
std::cout << i << std::endl;
}
A valid loop is also:
for (int a = 0, b = 10, c = 20; (a+b+c < 100); c--, b++, a+=c) {
std::cout << a << " " << b << " " << c << std::endl;
}
An example of hiding declared variables before a loop is:
int i = 99; //i = 99
for (int i = 0; i < 10; i++) { // we declare a new variable i
// some operations, the value of i ranges from 0 to 9 during loop execution
}
// after the loop is executed, we can access i with value of 99
But if you want to use the already declared variable and not hide it, then omit the declaration part:
int i = 99; //i = 99
for (i = 0; i < 10; i++) { // we are using already declared variable i
// some operations, the value of i ranges from 0 to 9 during loop execution
}
// after the loop is executed, we can access i with value of 10
Notes:
- The initialization and increment statements can perform operations unrelated to the condition statement, or nothing at all - if you wish to do so. But for readability reasons, it is best practice to only perform operations directly relevant to the loop.
- A variable declared in the initialization statement is visible only inside the scope of the
forloop and is destroyed when the loop ends. - Don’t forget that the variable which was declared in the
initialization statementcan be modified during the loop, as well as the variable checked in thecondition.
Example of a loop which counts from 0 to 10:
for (int counter = 0; counter <= 10; ++counter)
{
std::cout << counter << '\n';
}
// counter is not accessible here (had value 11 at the end)
Explanation of the code fragments:
int counter = 0initializes the variablecounterto 0. (This variable can only be used inside of theforloop.)counter <= 10is a Boolean condition that checks whethercounteris less than or equal to 10. If it istrue, the loop executes. If it isfalse, the loop ends.++counteris an increment operation that increments the value ofcounterby 1 ahead of the next condition check.
By leaving all statements empty, you can create an infinite loop:
// infinite loop
for (;;) {
std::cout << "Never ending!\n";
}
The while loop equivalent of the above is:
// infinite loop
while (true) {
std::cout << "Never ending!\n";
}
However, an infinite loop can still be left by using the statements break, goto, or return or by throwing an exception.
The next common example of iterating over all elements from an STL collection (e.g., a vector) without using the <algorithm> header is:
std::vector<std::string> names = {"Albert Einstein", "Stephen Hawking", "Michael Ellis"};
for (std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) {
std::cout << *it << std::endl;
}