Swift: While and Repeat-While

The while loop

The while function will run until the condition that is tested becomes false, thus the loop can run one time or multiple times. It is well suited when we don’t know how many times we should loop.

So let’s create a simple loop where we increment the numbers of steps by 2 until we reach 10 steps and when we reach it, we output a congratulation message.

Screen Shot 2017-04-15 at 17.06.33.png

So we have declared 3 different variables:

  • steps – which represent the number of steps we accomplish, we increment it by 2 for each loop
  • total – it will add up all the steps that have been made
  • target – represents the number of steps we must take, in order to succeed

So we will loop until the total number of steps will be the same as our target (in our case it is 5 times). Then, once we have reached our target, the output message is shown.

The while function has a particular case, the repeat-while loop.

The repeat-while loop

The repeat-while loop will repeat a statement while a condition is met. The difference between the two loops is that, repeat-while first runs the statement and then checks the condition. The while loop, will first check the condition and will run the statement only if the condition is true.

So if we take the example from above, and set the initial value for steps at 10, then the total number of steps that will be accomplished is 12 when we use the repeat-while loop and only 10 with the while loop.

Screen Shot 2017-04-15 at 17.06.33.png

 

 

 

 

 

2 thoughts on “Swift: While and Repeat-While

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: