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 trialRos Zunra
767 PointsAbout the while loop challenge
After I successfully completed the challenge(with the numbers.count method), I tried another way/expression but it didn't work out, which I don't get why.
Q: Given an array of numbers, print out each number in the array using a while loop and the println statement.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var dex = 0
while numbers[dex] < 11 {
println(numbers[dex])
dex++
}
Thank you!!
2 Answers
Greg Kaleka
39,021 PointsDid you actually write println(numbers[dex]) dex++
on one line like that? If so, that's your problem.
Edit: OK, now that I'm looking at this again, I see the issue. If you think about what will happen as you go through the while loop, you'll see what happens:
- 1st time through: checks if numbers[0], which is 1, is less than 11, which it is
-
2nd time through: checks if numbers[1], which is 2, is less than 11, which it is
...
10th time through: checks if numbers[9], which is 10, is less than 11, which it is
11th time through: checks if numbers[10] is less than 11 - gets an error because numbers[10] doesn't exist
Make sense?
Benjamin Zawodni
1,732 PointsDid you try this in Xcode? It looks like it's correct, and should work.
I've found that with these challenges they look at more than just the output sometimes. I suspect they want you to learn the "preferred" method.
Ros Zunra
767 PointsRos Zunra
767 PointsHi Greg, I actually broke them into 2 lines like this. Sorry I didn't notice the change in this post.
{println(numbers[dex])
dex++
}