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 trialJustus Aberson
1,035 PointsWhile loop question.
Hey guys, I was just wondering, why is the code im writing here not ok? Thanks.
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter < numbers.count {
counter++
sum = sum + (numbers[counter])
}
1 Answer
Henrik Brüntrup
5,485 PointsHi Justus,
arrays start at 0, not at 1. So your code should look like:
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter <= (numbers.count - 1) {
sum = sum + numbers[counter]
counter += 1
}
Adding array positions 0 though 6. Yours was 1 through 7, throwing an out of index range since you do not have a position 7 in your array.
Best regards, Henrik
Henrik Brüntrup
5,485 PointsHenrik Brüntrup
5,485 PointsYou might have to use
counter ++
as
counter += 1
is Swift 3.0 syntax.
Let me know if this works!
J.D. Sandifer
18,813 PointsJ.D. Sandifer
18,813 PointsJust to clarify for any folks new to programming reading this answer, flipping the order of
counter++
andsum = sum + numbers[counter]
was the main issue.The comparison
counter <= (numbers.count - 1)
is equivalent tocounter < numbers.count
. However,counter++
has been deprecated as Henrik pointed out in the next answer. You should usecounter += 1
instead.And just for fun,
sum = sum + numbers[counter]
can be re-written assum += numbers[counter]
for more brevity.