C++ While Loop

The while loop in C++ is used to repeatedly execute a block of code as long as a specified condition is true. It is commonly used when the number of iterations is not known beforehand.

The condition is checked before each iteration. If the condition becomes false, the loop stops executing.

Syntax

while(condition) {
    // code to be executed
}

How the While Loop Works

  • The condition is evaluated before the loop starts.
  • If the condition is true, the loop body executes.
  • After execution, the condition is checked again.
  • The loop stops when the condition becomes false.

Example Program

#include <iostream>
using namespace std;

int main() {

    int i = 1;

    while(i <= 5) {
        cout << "Number: " << i << endl;
        i++;
    }

    return 0;
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example: Countdown Using While Loop

#include <iostream>
using namespace std;

int main() {

    int count = 5;

    while(count > 0) {
        cout << count << endl;
        count--;
    }

    return 0;
}

Important Notes

  • The condition must eventually become false; otherwise, the loop will run forever (infinite loop).
  • The loop variable must be updated inside the loop.
  • The while loop is useful when the number of iterations is unknown.

Next Topic

Next, learn about C++ Do While Loop.