C++ While Loops



This is a tutorial on C++ While loops.

The C++ while loop has two components, a condition and a code block. The code block may consist of a single statement or a block of statements, and the condition defines the condition that controls the loop. The condition may be any valid Boolean expression.

The loop repeats while the given condition is true. When the condition becomes false, the loops terminates and program control passes to the line immediately following the loop.


Syntax

Below is the general code for creating a while loop. The C++ while loop first checks the condition, and then decides what to do. If the condition proves to be false, the instructions in the code block will not be executed.

while (condition) {
   // Instructions be executed
}

C++ While Loop Example

A basic example of the C++ while loop.

#include <iostream>
using namespace std;

int main()
{
    int x = 0;

    while (x < 5) {
        cout << x << endl;
        x = x + 1;
    }
    return 0;
}
0
1
2
3
4

As shown above, the while loop printed out all the numbers from 0 to 4. The loop terminated once the value of x reached 5, before the output statement was even reached. Hence 5 was not included in the output.


While Loops with multiple conditions

While loops in their most basic are useful, but you can further increase their ability through the use of multiple conditions.

You can chain together multiple conditions together with logical operators in C++ such as && (And operator) and || (Or operator). What you’re really doing is creating a longer equation that will return either True or False, determining whether the loop executes or not.

As a brief recap, with the && operator both conditions must be True for it to return True. For the || operator, as long as at least one condition is True, it will return true.

#include <iostream>
using namespace std;

int main()
{
    int x = 0;
    int y = 0;

    while (x < 5 &amp;&amp; y < 6) {
        x = x + 1;
        y = y + 2;
        cout << "X: " << x << " ";
        cout << "Y: " << y << endl;
    }
}
X: 1 Y: 2
X: 2 Y: 4
X: 3 Y: 6

This marks the end of the While Loops in C++ article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *