TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.