# How Do-While Loops Work in Computer Programming

When you’re learning to program, understanding the basic building blocks is key to early success. You’ll pick up the difficult topics later, but if you don’t understand variable types, loops, and functions, it’s tough to get far.

Most new programmers learn about if-else statements, while loops, and for loops before long. But one of the loop types you might not understand is the do-while loop. Let’s discuss how this loop works, when you’ll want to use it, and look at a few examples.computer science computer science computer science computer science computer science

### The Basics

A do-while loop executes a block of code at least once, checks if a condition is true, then continues to run the code inside depending on the condition.

```do {
output "The variable x equals " + x;
x++;
} while (x < 5);

output "The loop has ended.";
```

In this bit of code, the lines inside the do brackets always run at least once. This means that x could be any value at the start of the loop.computer science computer science computer science computer science computer science

If x equals 1 when the loop starts, it will repeat until x does not satisfy the condition next to while. Thus, it would run a total of 5 times. When x is not less than 5, the loop ends and continues onto the code after it. This output would look as follows:

`The variable x equals 1 The variable x equals 2 The variable x equals 3 The variable x equals 4 The variable x equals 5 The loop has ended.`

Conversely, if x was equal to 20 when this loop started, it would only run once. So you would see one output statement, x increments to 21, and the loop would end because 21 is not less than 5. Its output would be:

```The variable x equals 20 The loop has ended.
```