While Loops in C++

This is the reference section for while loops as they are used in the C++ programming language. The general while loop statement consists of single conditional that determines when to stop looping. While loops have two variants: while and do-while.


Video Tutorials

Lesson 8: While and Do While Loops

 

Example 1

// This while loop mimicks the style of a for loop.
// This code outputs the integers 0 through 9.
// This shows how to use a while loop, but a for loop is more appropriate.
int iJ = 0;
while (iJ < 10) {
    std::cout << iJ << std::endl;
    ++iJ;
}

Example 2

// This while loop uses a boolean variable as a condition.
// This code outputs the integers 0 through 9.
// This is a more typical while loop usage, but the circumstance is contrived.
int iJ = 0;
bool bDone = false;
while (!bDone) {
    std::cout << iJ << std::endl;
    ++iJ;
    if (iJ >= 10) {
        bDone = true;
    }
}

Example 3

// This while loop is infinite without the break statement.
// This code outputs the integers 0 through 9.
// This demonstrates the usage of a break statement to exit a loop.
int iJ = 0;
while (true) {
    std::cout << iJ << std::endl;
    ++iJ;
    if (iJ >= 10) {
        break;
    }
}

Example 4

// This is a do-while loop that executes once.
// This code outputs 100 and increment iJ to 101 inside the loop.
// Even though the condition is false, a do-while loop will always execute atleast once.
int iJ = 100;
do {
    std::cout << iJ << std::endl;
    ++iJ;
} while (iJ < 10);

Example 5

// This do-while loop is infinite without the break statement.
// This code outputs the integers 0 through 9.
// This demonstrates the usage of a break statement to exit a loop.
int iJ = 0;
do {
    if (iJ >= 10) {
        break;
    }
    std::cout << iJ << std::endl;
    ++iJ;
} while (true);