BLACK FRIDAY SALE: 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

   

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.

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.