Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Collections and Control Flow Control Flow With Loops Working with Loops

whats wrong?

dont understand whats wrong with this code

while.swift
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0


while counter < numbers.count {
  sum += (numbers.count)
  counter++ }


while counter < numbers.count {
    sum = sum + numbers[counter]
    counter++
}
// Enter your code below

2 Answers

Keli'i Martin
Keli'i Martin
8,227 Points

I'm not sure why you have two while loops but you don't need the first one at all. The second while loop has the exact code you need to pass the challenge.

Tobias Helmrich
Tobias Helmrich
31,601 Points

Hey there,

the code of the second while loop is actually perfectly fine! The first one however is wrong because you're just adding the length of the numbers array to the sum variable all the time but you have to add the value at the current index to the sum variable which you're doing correctly in the second loop. The first while loop is also the reason why you're not passing the challenge, so if you remove it, it should work!

while counter < numbers.count {
    sum += numbers[counter]
    counter++
}

I hope that helps! :)