Start learning free

LESSON 117 OF 349 · WHILE LOOPS & FOR LOOPS

While loop: Printing more numbers in Swift in Swift

Lesson

Practice makes perfect! Let's check two more examples of printing numbers using the while loop.


Example 1:

Let's print all the even numbers from 4 through 14:

var i = 4
while i <= 14 {
	print(i)
	i += 2
}

The output of this program is:

4
6
8
10
12
14

Example 2:

We can also loop in reverse. Let's print all even numbers from 12 to 4 in decreasing order:

var i = 12
while i >= 4 {
	print(i)
	i -= 2
}

The output of this program is:

12
10
8
6
4

Assignment
Let's print all the odd numbers from 23 to 7 in decreasing order!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

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