Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Collections and Control Flow Control Flow With Loops While and Repeat While

While and Repeat While

I was playing around in x code with While and Repeat While and the following let me a little confused. If someone could explain the results to me I would really appreciate it:

so sample 1:

var x = 0

while x <= 20 { print (x) x ++ }

by doing this, it shows in Xcode that the loop runs 21 times. first with 0 through to 20 and prints. Simple enough and that makes sense to me.

Sample 2, I switched the x++ first before print. Thoughts were that it would run 20 times as it would add to x first and then determine it was less than 20 and then print. Code as follows:

var x = 0 while x <= 20 { x ++ print (x) }

the results surprised me. It still ran 21 times, and it printed the numbers 1 - 21. My questions is why would it print the number 21? I thought that it would hit 20 add the 1 and then wouldn't print as it wasn't <= 20. However it did print it.

Thank you to anyone who can give me some help.

3 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Well let's take a look at that again:

var x = 0 
while x <= 20 {
 x ++ 
print (x) 
}

Let's say that you're on the very last loop. x is now equal to 20. It's still going to run. And what's going to happen? First it's going to increment x. So x is now equal to 21. And now it prints x, which is 21 :smiley: And there you go!
:sparkles:

edited for additional note

I think maybe the thing you might be confusing here is that it only reevaluates x after it gets to the bottom of the code in the loop. It does not reevaluate the original condition at every change of x. It waits until it gets up to the top and does the evaluation again with the current value of x.

check this out you might understand

var x = 0 x++ while x <= 20 { print (x) }

Thank you for giving me another way to look at it Sandeep.

you're welcome Andrew.

Thank you for your help Jennifer. You're right about where I was confused. I thought it would reevaluate in the loop, so on the last loop where it's 20, I had thought that it would notice the number now being 21 and not printing as it does not meet the case of being <= 20.