NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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

   

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

   

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.

   

Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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

Reply to this topic…

You need to create an account or log in to reply.

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.