C++ While Loop

C++ While Loop

Loops can execute a block of code as long as a specified condition is reached. They are handy because they save time, reduce errors, and make code more readable.

The while Loop

The while loop loops through a block of code as long as a specified condition is true.

Example

int i = 0;
while (i < 5) {
  cout << i << "\n";
  i++;
}

In the example above, the code in the loop will run, over and over again, as long as i is less than 5. Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end (an infinite loop)!

The do/while Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Example

int i = 0;
do {
  cout << i << "\n";
  i++;
}
while (i < 5);

Use loops whenever you need to repeat an action multiple times!


Exercise

?

Which variant of the while loop guarantees that the code block will execute at least once?