๐ŸŽ“ A1Learner
๐Ÿ”

C++ While Loop

A while loop is a loop that repeats a block while a condition stays true. The condition is checked before each run of the block.

Counting up

The counter starts at 1. The loop prints the counter, then adds 1.

#include <iostream>

int main() {
  int count = 1;
  while (count <= 3) {
    std::cout << count << std::endl;
    count++;
  }
  return 0;
}

Counting down

The counter starts at 3. The loop prints the counter, then takes 1 away.

#include <iostream>

int main() {
  int count = 3;
  while (count >= 1) {
    std::cout << count << std::endl;
    count--;
  }
  return 0;
}

Adding in a loop

The total starts at 0. Each run adds the next number to the total.

#include <iostream>

int main() {
  int number = 1;
  int total = 0;
  while (number <= 4) {
    total += number;
    number++;
  }
  std::cout << total << std::endl;
  return 0;
}

Example

#include <iostream>

int main() {
  int count = 1;
  while (count <= 3) {
    std::cout << "3 x " << count << " = " << 3 * count << std::endl;
    count++;
  }
  return 0;
}

Key points

  • The while keyword starts the loop.
  • The condition sits in parentheses after while.
  • The block runs again while the condition stays true.
  • A statement in the block can change the value the condition tests.
  • A total can grow by one piece on each run.

In this example, count starts at 1. Each run prints one line of the 3-times table. The loop stops after the line for 3.

Note

A while loop may run zero times if the condition starts false.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

In a while loop, when is the condition checked?