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

Not sure how to write this while clause

Don't get how to do this.

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


// Enter your code below
sum == numbers.count


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

3 Answers

Ibrahim M.
Ibrahim M.
11,797 Points

Ok, the code below is what you are looking for, and just a few points to clarify what's happening:

  1. Counter starts at 0. It's the index we will use to access items inside the numbers array.
  2. numbers.count returns the number of items/numbers inside the numbers array, in our case it would return 7 as we have 7 numbers inside the array.
  3. numbers[counter] returns the number in the array at index 'counter'. That index starts at 0. ex: numbers[0] = 2, numbers[1] = 8, etc... numbers[6] = 9
  4. So we make a while loop, that has a condition where the counter we use should go through the number of items/numbers inside the "numbers" array.
  5. The summation is taking the previous sum and adding in the new value found in the array (see #3)
  6. We then increment the counter by 1, to go to the next index position in the array.
  7. When the 'counter' value equals numbers.count, the loop ends immediately.
  8. We use less than (< strictly) and not less than or equal (<=) because array indexes start at 0.
// Enter your code below

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

// Print out the result: should be 43
print(sum)

When I tried, it still didn't work:

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

// Enter your code below

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

print(sum)

priya x
priya x
866 Points

The above code is right but for some reason it's only recognizing the counter increment counter++. Change counter+=1 to the increment operator and it works.