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 trialDaniel Lambrecht
iOS Development Techdegree Student 5,302 Pointshow to use counter to choose which item in the array to add?
ive tried several combinations: sum += numbers[(counter)] sum += numbers[(counter)] sum += numbers[counter]
im lost :D
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter <= sum {
sum += numbers[(counter)]
counter += 1
}
1 Answer
andren
28,558 PointsYou don't need to have parenthesis around the counter
variable but that is not actually what causes an issue with your code. The problem is that the condition for the loop is incorrect. The loop is meant to run while counter
is less than the number of items in the numbers
array. Your looping condition states that it should run until it is less than or equal to the sum
variable, which is incorrect.
You can get the number of items in the numbers
array using the count
property so the loop should look like this:
while counter < numbers.count {
sum += numbers[counter]
counter += 1
}
Other than the condition (and the unnecessary parenthesis) your code was correct.
Daniel Lambrecht
iOS Development Techdegree Student 5,302 PointsDaniel Lambrecht
iOS Development Techdegree Student 5,302 PointsWow, thank you so much!! :)