C++ while loop

In C++, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. The loop checks the condition before each iteration, and if the condition is true, the code inside the loop is executed. Once the condition becomes false, the loop terminates.

Syntax:


while (condition)
{
    // Code to execute as long as condition is true
}

Explanation:

condition: A boolean expression that is checked before each iteration. If it is true, the loop continues; if false, the loop terminates.

Note: If the condition is false initially, the loop won’t execute at all.

Example:


#include <iostream>
using namespace std;

int main() {
    int count = 1;
    
    while (count <= 5) {  
        cout << "Count is: " << count << endl;
        count++;  // Increment the count variable to eventually stop the loop
    }
    return 0;
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Explanation:

1. The while loop keeps running as long as count is less than or equal to 5.

2. Each time the loop runs, it prints the value of count and then increments it by 1.

3. The loop will stop once count reaches 6.