For Loops in C++

This is the reference section for for-loops as they are used in the C++ programming language. The general for loop statement consists of three basic parts: initialization, conditional, and update.


Video Tutorials

Lesson 16: For Loops

 

Example 1

// A simple for loop with initialization, conditional, and update.
// This code outputs the integers 0 through 9.
for (int iJ = 0; iJ < 10; ++iJ) {
    std::cout << iJ << std::endl;
}

Example 2

// A for loop without the initialization step.
// This code outputs the integers 0 through 9.
// It demonstrates that the initialization does not need to happen inside the for.
int iJ = 0;
for (; iJ < 10; ++iJ) {
    std::cout << iJ << std::endl;
}

Example 3

// A for loop without the initialization and a different conditional.
// This code outputs the integers 0 through 9.
// It demonstrates the versatility of the conditional.
bool bDone = false;
int iJ = 0;
for (; !bDone; ++iJ) {
    std::cout << iJ << std::endl;
    if (iJ >= 9) {
        bDone = true;
    }
}

Example 4

// A for loop with only a conditional.
// This code outputs the integers 0 through 9.
// It is equivalent to a while loop.
bool bDone = false;
int iJ = 0;
for (; !bDone;) {
    std::cout << iJ << std::endl;
    if (iJ >= 9) {
        bDone = true;
    }
    ++iJ;
}

Example 5

// An empty for loop.
// This code outputs the integers 0 through 9.
// Without the break statement, this would be an infinite loop.
int iJ = 0;
for (;;) {
    std::cout << iJ << std::endl;
    if (iJ >= 9) {
        break;
    }
    ++iJ;
}

Example 6

// A for loop with only an initialization.
// This code outputs the integers 0 through 9.
// This is strange, but demonstrates the versatility of the for loop.
for (int iJ = 0; ;) {
    std::cout << iJ << std::endl;
    if (iJ >= 9) {
        break;
    }
    ++iJ;
}