Get startedGet started for free

While loops

1. While loops

Finally, let's quickly discuss while loops!

2. While loops are simpler

The while-loop is conceptually simpler than the for-loop we've seen previously and is only made of two components: a continue condition and a loop body. As long as the condition is met, the loop continues and the body is executed.

3. Example

In this function, we calculate the smallest power of two that is greater to a given number n. We start by initializing the value variable outside the while loop. Then we keep doubling the value until it is no longer lower than n. Therefore we have calculated the smallest power of two that is greater than n.

4. For loops are just while loops

The for-loop we've seen previously in this chapter can alternatively be expressed as a while-loop. The for-loop is idiomatic when, for example, processing all values from a vector, but sometimes a while-loop makes more sense.

5. do / while loops

Another alternative is the "do/while loop". The difference with the while-loop is that the condition comes after the body. This is particularly useful when the body must always run at least once.

6. Example of a do / while loop

The previous example might be written as a "do/while loop". The loop form you use depends on your use case, so it is good to know about the various ways of iterating. However, for most practical uses, you will end up with a for-loop.

7. Let's practice!

Now let's try some examples.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.