Start learning free

LESSON 116 OF 349 · WHILE LOOPS & FOR LOOPS

While Loop: Printing Numbers in Swift in Swift

Lesson

We can achieve many different outcomes with while loops.

For example, we can print print all the numbers from 0 through 4:

var i = 0
while i < 5 {
	print(i)
	i += 1
}

The output of this program is:

0
1
2
3
4

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

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 5 true? <=> Is 0 < 5 true? Yes.
	b. print(i) => Output: 0
	c. i += 1 => i = 1

1. Second iteration:
	a. Is i < 5 true? <=> Is 1 < 5 true? Yes.
	b. print(i) => Output: 1
	c. i += 1 => i = 2

2. Third iteration:
	a. Is i < 5 true? <=> Is 2 < 5 true? Yes.
	b. print(i) => Output: 2
	c. i += 1 => i = 3

3. Forth iteration:
	a. Is i < 5 true? <=> Is 3 < 5 true? Yes.
	b. print(i) => Output: 3
	c. i += 1 => i = 4

4. Fifth iteration:
	a. Is i < 5 true? <=> Is 4 < 5 true? Yes.
	b. print(i) => Output: 4
	c. i += 1 => i = 5

5. Sixth iteration:
	a. Is i < 5 true? <=> Is 5 < 5 true? No.
	b. Exit the loop.

Assignment
Let's print all numbers from 3 to 10 using a while loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    Printing Numbers 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