Workshop 22: The While and Do-While Loop

In this workshop you learn how to us the while and do-while loop to execute a block of code until a condition is met.

Before you begin, I assume you have done the following:

workshop16-fig00

The While Loop

A while loop evaluates a condition. If it evaluates to true then code in the while block {} are executed. After the code have executed the condition is evaluated again and the loop continue until the condition evaluates to false. The while loop block must feature code that will affect the test condition in order to change the evaluation result to return false; otherwise, an infinite loop will be created.

notebook An infinite loop will crash the iOS app. For example, leaving out this statement: counter++; in the code block will cause an infinite loop. The while loop is use a lot to process database records.

If the test condition evaluates to false when it is first executed then code in the while block is never executed. A while loop is known as a post-test loop and it is done like this:

Code below demonstrate how to use a while loop. The counter variable is incremented on each iteration of the loop until it reaches 5 when the condition (counter < 6) is evaluated to false and the loop ends.

// Declare and initialize an Int counter variable
var counter = 1;
//loop until counter is equal to 5
while counter < 6 {
  //display the counter variable value
  println("counter is now \(counter)")
  // increment the counter by 1
  counter++
}
Output

Above code will produce the following output in the playground’s Timeline.

counter is now 1
counter is now 2
counter is now 3
counter is now 4
counter is now 5

The do-while Loop

The do-while loop execute a block of code repeatedly until an condition evaluates to true. Code in a do-while is executed once before the condition is evaluated. On the second iteration of the do-while loop, if the condition evaluates to true code in the block { } is executed. The do-while loop block must feature code that affect the test condition; thus making it evaluate to false, otherwise an infinite do-while loop will be created. A do-while loop is known as a pre-test loop and it is done like this:

Code shown in the image below demonstrate how to use the do-while loop. The image also shows result of the code in the iOS Simulator.

workshop22-fig01