While and Do While Loops

A while loop is a way of repeating a section of code while a condition is true. While loops have two main parts; the condition and the code that will be repeated and executed. A while loop is similar to a for loop, all for loops can be represented as a while loop. However, not all while loops can be represented as a for loop.

A while loop has a condition, similarly to a for loop, but a while loop can use any condition that evaluated to a boolean value. This means we can use a single boolean variable within the while loops conditions, whereas a for loop can only be used with numbers. Although, while loops can be used for counting too, as long as the condition is a boolean value.

Below are a few examples of while loops, make sure you understand why and how the looping works even if you don’t fully understand the code.

This will print the following values: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

This will print the word “hello” indefinitely. This is referred to as an infinite loop, as the loop never exits. Infinite loops can be dangerous as it will halt the programs execution.

This will print the word “hello” once.

A do while loop will execute the code in the execution block once, even if the condition evaluates to false. This is the difference between a normal while loop and a do while loop. A do while loop will always execute the code once, regardless of the condition.

The below do while loop will print the following numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

The below do while loop will only print the following number: 0. This is because the condition evaluates to false.

Leave a Reply