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 trialTAYLOR HENSLEY
975 PointsUsing a while loop and the print ln statement
I don't understand what is going wrong. When I don't use index++ it says my program is running too long And when I do, it says Error.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let index = 0
while index < numbers.count {
println(numbers[index])
index++
}
1 Answer
Richard Lu
20,185 PointsYour programs while condition is always satisfied if the index++ isn't there.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var index = 0 // CHANGE THIS FROM A CONSTANT TO A VARIABLE (IT MUST CHANGE)
while index < numbers.count {
println(numbers[index])
index++
}
index++ is a short version of index = index + 1, and this changes the index value. When the loop goes back to the next iteration, it checks whether the index satisfies (index < numbers.count). If you don't place index there, index will always be equal to 0, and 0 is always less than numbers.count.
Christopher Augg
21,223 PointsChristopher Augg
21,223 PointsGood explanation.
Tyler Amend
2,236 PointsTyler Amend
2,236 PointsExcellent answer, but just to further comment. Using "Let" declares a constant, which cannot be manipulated later in the program. This is useful for things that will never change within your program. For a really broad example we could use the area of a room. That area will never get larger. If it's data that you are planning to manipulate, it's best stored in a "var".