LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 6 Checkpoint 3: while loops question 8

Forums > 100 Days of SwiftUI

I get 4 lines, not 5. What am I missing?

var number: Int = 10
while number > 0 {
    number -= 2
    if number % 2 == 0 {
        print("\(number) is an even number.")
    }
}
  1. number is 10, subtract 2, number is 8, prints 8 is an even number (line 1)
  2. subtract 2, number is 6, prints 6 etc (line 2)
  3. -2 = 4, prints 4 is etc (line 3)
  4. -2 = 2, prints 2 is an even number (line 4)

-2 = 0, number is NOT > 0; end

2      

Have you run it or only tried working it out in your head? It prints 5 lines because number does not get decremented to 0 until you are already inside the loop, past the check, when number == 2.

So, it's:

  1. number is 10, while condition passes, subtract 2, number is 8, prints 8 is an even number (line 1)
  2. number is 8, while condition passes, subtract 2, number is 6, prints 6 etc (line 2)
  3. number is 6, while condition passes, subtract 2, number is 4, prints 4 etc (line 3)
  4. number is 4, while condition passes, subtract 2, number is 2, prints 2 etc (line 4)
  5. number is 2, while condition passes, subtract 2, number is 0, prints 0 etc (line 5)
  6. number is 0, while condition fails, end of loop

2      

number does not get decremented to 0 until you are already inside the loop

perfect. brain fog day; knew I was missing something obvious.

yes, working it in my head, not running it.

2      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.