C++ while Loop

In this lesson, you will learn about C++ while loop with a few examples.


C++ while Loop

Below is the syntax of the while loop in C++

Basic syntax

while (condition) {
// body of the while loop
}

In the basic syntax of the while loop,

  • A while loop assesses the condition.
  • The while loop’s body is executed if the condition evaluates to true.
  • The condition is once more assessed. Until the condition is false, this process keeps going. The loop ends when the condition is evaluated as false.

Example

//Program prints 3 integers
#include <iostream>

using namespace std;
int main() {
  int number = 3;
  while (number >= 1) {
    cout << number << " ";
    number--;
  }
  return 0;
}

Output

3 2 1

That’s how the program performs

VariantVariable Updatenumber >= 1Action
1stnumber = 3True3 is printed. The number is decreased to 3.
2ndnumber = 2True2 is printed. The number is decreased to 2.
3rdnumber = 1TrueOne is printed. The number is decreased to 1.
4thnumber = 0falseProgram terminated

This concludes the C++ while loop lesson. The next lesson will learn about the “do while” in C++.