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

Variant Variable Update number >= 1 Action
1st number = 3 True 3 is printed. The number is decreased to 3.
2nd number = 2 True 2 is printed. The number is decreased to 2.
3rd number = 1 True One is printed. The number is decreased to 1.
4th number = 0 false Program terminated

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