for loop

suggest change

A 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:

The rough equivalent of a for loop, rewritten as a while loop is:

/*initialization*/
while (/*condition*/)
{
    // body of the loop; using 'continue' will skip to increment part below
    /*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:

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:

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;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents