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 trialJosh Schlabach
1,771 PointsGiven an array of numbers, print out each number in the array using a while loop and the println statement- Help me!!
i can't figure this out
1 Answer
Ben Griffith
5,808 PointsSo in order to iterate through our array, we need to create a counter which will also act as the index that will keep track of how many times we've looped.
var index = 0
Next step is to build the while loop. In this task, we want to loop over all the values. We can use count method of the array in order to make sure we only loop as many times as needed.
while index < nameOfArray.count {
}
If you ran this, the loop would run forever. To fix this we need to include the index and increment it by 1.
while index < nameOfArray.count {
index++
}
Finally add your print statement inside the loop - use the index to target the correct value within the array.
while index < nameOfArray.count {
println( nameOfArray[index] )
index++
}
Josh Schlabach
1,771 PointsJosh Schlabach
1,771 PointsThanks so much! :D