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 trialVic Ward
4,876 PointsWhat's wrong with my code?
Trying to complete this challenge...I just don't know how!
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter <= numbers.count {
var newValue = numbers[counter]
sum = sum + newValue
counter++
}
2 Answers
Chase Marchione
155,055 PointsHi Vic,
We want to have the while loop run while counter is less than numbers.count, rather than less than or equal to (if the values are equal, that would mean that we don't have another value left to add to the sum.)
I recommend removing the newValue variable altogether (though if we did keep the newValue variable, we'd want to write the declaration of it outside of the while loop: otherwise, the compiler would attempt to redeclare newValue every time that the loop is run), since we can accomplish what we want to do without that extra variable (and therefore, extra lines of code.)
while counter < numbers.count {
sum += numbers[counter]
counter++
}
Hope this helps!
Vic Ward
4,876 PointsThank you so much, really appreciate it.