Quick Swift Challenge

True or False: This While Loop will print 5 lines of text.

var page: Int = 0
while page <= 5 {
	page += 1
	print("I'm reading page \(page).")
  • if you need to, write it out in a REPL http://repl.it
    ** I got this correct, but I’m not sure I understand the answer!
1 Like

Hello! I will assume your answer was false. Here is an explanation:
This loop iterates while page is less than or equal to five. Therefore, on the first iteration, page is 1; that works. Then it is 2; that works. Then 3, 4, 5; you would expect that. The last one is more unexpected.

Due to the placement of the page+=1, page equals 6 before the loop ends-meaning the rest of the code within the loop must be iterated through before the condition (while page <= 5) is evaluated again. That means I'm reading page 6 gets printed before the loop ends.

I hope this helps!


Yes, beautifully stated, @codeneutrino :slight_smile:

I reviewed it a little bit by building it and tearing it apart, and rebuilding in a REPL and understand why there are 6 print lines instead of 5, like I originally thought… :laughing:

Thank you for taking the time to write that out so concisely!

1 Like