C++ Do While Loop

The do-while loop is a type of loop in C++ that is used to execute a block of code repeatedly until a certain condition is met.

The syntax for the do-while loop is as follows:

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

Here’s how the do-while loop works:

  1. The code inside the curly braces {} is executed first, regardless of the condition.
  2. After the code inside the curly braces is executed, the condition inside the parentheses () is evaluated.
  3. If the condition is true, the code inside the curly braces is executed again. This process continues until the condition becomes false.
  4. If the condition is false, the do-while loop terminates and the program continues with the next line of code.

One important thing to note about the do-while loop is that the code inside the curly braces will be executed at least once, even if the condition is false from the beginning.

Let’s take a look at an example of how the do-while loop works:

#include <iostream>

int main() {
  int i = 0;
  do {
    std::cout << i << " ";
    i++;
  } while (i < 5);

  return 0;
}

In this example, the program will output the numbers from 0 to 4, since the condition i < 5 is true for those values of i. The output of the program will be:

0 1 2 3 4

Even though the condition i < 5 is false when i is 5, the code inside the curly braces is still executed one last time before the do-while loop terminates.

The do-while loop is useful when you want to execute a block of code at least once, and then continue executing it while a certain condition is true. It’s also helpful when you don’t know how many times you’ll need to execute the code, but you know you need to execute it at least once.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial