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 trial

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

Haitham Alam
Haitham Alam
2,685 Points

Sorry I can not guess the right answer, can I have it explained please??

I can not guess the right answer, can I have it explained please??

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

numbers.count

var counter = (numbers.count)

while sum < counter {
    print ("counter")
    sum++

  }

3 Answers

Haytham, first, you need to create a condition so the loop will run once for each element in the array. Treehouse gave you a loop counter, starting at 0. So the loop needs to run until that counter equals the index of the last element in the array, which is numbers.count - 1, i.e., < numbers.count. Then, each time through the loop, you need to add the value of the element to sum: sum += numbers[counter]. To get the value of each element you need to use subscript notation: numbers[counter]. Finally, you need to increment counter each time through the loop so you traverse the array: counter++. Note that sum is what is called an accumulator because it occurs on both sides of the assignment operator: sum = sum + numbers[counter], which is the longer version of sum += counter.

while (counter < numbers.count) {
  sum += numbers[counter]
  counter++;
} 
Haitham Alam
Haitham Alam
2,685 Points

thanks but it does not work and I am getting error saying "Bummer! Make sure your condition allows for iteration over all elements in the numbers array and check your calculation of sum"

Not sure what to say. I just tested it again and Treehouse came back with "Well, done!.." Suggestion. Close your browser completely, and then go back to the Challenge page and then replace everything in the code window with the following:

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

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

I found on several occasions that if I did something wrong the browser seemed to cache my wrong answer and subsequent corrections were ignored. It has only happened a couple of times, although I've made many more errors than that, so it may be something else. But it doesn't hurt to start with a truly clean slate! Just make sure that there's no other code than the above after you copy it and paste it in.