Learn
Loops
do..while Loop

A do..while loop is just like a while loop except the looping condition is checked at the end of the loop body. This is known as an exit-condition loop and means the code in the body will execute at least once:

val myCondition = false do { print("I loop once!") } while(myCondition)

This example shows that even though we have a false condition our loop will still run the loop body once:

I loop once!!!!

One reason we would use a do..while loop is when our loop condition initialization and update commands are the same. Using psuedocode we can compare a while loop with a do..while loop using how someone might decide to go outside:

Is it sunny outside?
while ( not sunny ) {
  Is it sunny outside?
  Stay inside.
}
Go outside!

The while loop example has a line before the loop to check if it is sunny outside. The loop is entered if it is not sunny and then repeatedly checks if it is sunny outside. When it is sunny, the loop exits and it’s time to go outside:

do {
  Is it sunny outside?
  Stay inside.
} while ( not sunny )
Go outside!

The do..while loop enters the loop and starts by checking if isSunny is true. The loop body repeats if the isSunny is false.

The extra check prior to the loop is unnecessary since it is performed inside the loop anyway. If we have to look outside to get our initial loop condition and to update our loop condition, we might as well have that be the loop body and check the condition at the end.

This difference may seem subtle, but if this loop is executed hundreds or thousands of times a second, removing the one line of code using a do..while loop may save time.

Instructions

1.

We’ll implement a do..while loop that performs a Celsius to Fahrenheit temperature conversion.

First, construct a do..while loop that checks if fahr does not equal 212.0. Inside the loop body:

  • paste the following 2 lines of code.
    fahr = celsiusTemps[index] * fahr_ratio + 32.0 println("${celsiusTemps[index]}C = ${fahr}F")
  • increment the value of index.
Folder Icon

Take this course for free

Already have an account?