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 trialPeter Bozic
453 Pointswhy does the loop stop after 10?
hi, I got the answer right but I don't quite fully understand the concept.
So the index looped from index 0 (1) to index 9 (10). my question is, if it's a loop then why doesn't it keep looping, why does it stop at number 10 and not start counting again from number 1 (if that makes sense)? Also, I would have thought that there would be code to instruct the code to stop looping at a certain point. It's probably a silly question but there it is anyway. Thanks
var index = 0
while index < numbers.count { println(numbers[index]) index++ }
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3 Answers
Devin Scheu
66,191 PointsWhile index which is 0, is less than the numbers array length, the loop increases the index by one and prints the number that is at that index. When index hits 10, index is no longer less than the numbers array length so the loop stops. I hope this makes sense.
Peter Bozic
453 Pointshi Devin, thanks for your help, yeah, sort of makes sense but just a bit difficult to fully comprehend. when index hits 9 that is number 10 and when index hits 10 that should be number 11 which is not in the array so it stops looping, this is my thinking but not sure I'm right. In any case, why doesn't it just go back to index 0 and start the count again? where is the command to say stop the loop?
Devin Scheu
66,191 PointsIt is built into the loop, when it stops index is no longer being increased by one, and it stays the same, if you viewed the contents of index you would see that it would be 9 because and array starts with 0. It is a difficult concept to grasp at first but we use the analogy of a baby, when you were born you were 0 years old right? So you start at 0 and work your way up to your current age.
Peter Bozic
453 PointsThanks Devin, I get it now, I'm probably thinking too much into it. Thanks for the explanations. cheers