Cpp - Statement while Loops

Introduction

A while loop repeats a group of statements as long as a starting condition remains true.

The while keyword is followed by an expression in parentheses.

If the expression is true, the statements inside the loop block are executed. They are executed repeatedly until the expression is false.

Here's a while loop that displays the numbers 0 through 99:

int x = 0; 
while (x < 100) 
{ 
    std::cout << x << "\n"; 
    x++; 
} 

The while keyword is followed by an expression within parentheses. This statement does not end in a semicolon.

The loop has the conditional expression x < 100.

Each time that x is less than 100, the body of the loop is executed, and the value of x is displayed.

When x is equal to 100, the loop ends.

Without the x++ increment statement, the value of x would remain 0, and the loop would never end. This is called an infinite loop.

Demo

#include <iostream> 

int main() /*from   w  w w. j  a  va2s . co  m*/
{ 
    int counter = 0; 
   
    while (counter < 500) 
    { 
           counter++; 
           if (counter % 13 == 0) 
            { 
                std::cout << counter << " "; 
            } 
    } 

    std::cout << "\n"; 
    return 0; 
}

Result

Related Topics

Exercise