Start learning free

LESSON 123 OF 349 · WHILE LOOPS & FOR LOOPS

Infinite for loops in Swift in Swift

Lesson

Remember the infinite while loop? Well, there is also such a thing called the infinite for loop.

Here is an example:

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

This is what happens during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 10 true? <=> Is 0 < 10 true? Yes.
	b. Run the code inside {}:
        1) print(i) => Output: 0
	      2) i -= 1 => i becomes -1
        3) i += 1 => i becomes 0 again

2. Second iteration:
	a. Is i < 10 true? <=> Is 0 < 10 true? Yes.
	b. Run the code inside {}:
        1) print(i) => Output: 0
	      2) i -= 1 => i becomes -1
        3) i += 1 => i becomes 0 again

3. Third iteration:
	a. Is i < 10 true? <=> Is 0 < 10 true? Yes.
	b. Run the code inside {}:
        1) print(i) => Output: 0
	      2) i -= 1 => i becomes -1
        3) i += 1 => i becomes 0 again

...

Assignment
Follow the Coding Tutorial and let's practice with infinite for loops!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Infinite For Loops 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