Start learning free

LESSON 115 OF 349 · WHILE LOOPS & FOR LOOPS

While loop in Swift in Swift

Lesson

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while condition {
	instruction1
	instruction2
	...
}

Let's check an example:

var count = 1
while count <= 5 {
	print("I made a mistake")
	count += 1
}
print("Finished!")

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 2

2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 3

3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 4

4. Forth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 6

6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No.
	b. Terminate the loop.


7. print("Finished!"); => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    The While Loop in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free