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

Cody Lynn
Cody Lynn
4,184 Points

Code Challenge: Working with Loops

I am having difficulty answering this question...

"Challenge Task 2 of 2

Now that we have the while loop set up, it's time to compute the sum! Using the value of counter as an index value, retrieve each value from the array and add it to the value of sum.

For example: sum = sum + newValue. Or you could use the compound addition operator sum += newValue where newValue is the value retrieved from the array."

Help would be greatly appreciated!

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

while counter < 7 {
print(numbers)
counter++
}
// Enter your code below

3 Answers

Cody, first you want to try to avoid what are called "magic numbers", like your 7. What is someone adds another number or so to the array, or deletes one? numbers.count will change automatically. Second, the challenge didn't ask you to print anything. It asked you to sum up the numbers in the array. sum += numbers[counter] takes each value of counter (0 to 6), accesses the array at that index, gets the value, and adds it to sum. sum += x is the same as sum = sum + x. Then, to stay out of an infinite loop, and to get to each element of the array, counter needs to be incremented. So first it is 0, then 1, then 2, etc.

// Enter your code below
while counter < numbers.count {
  sum += numbers[counter]
  counter++
}
Cody Lynn
Cody Lynn
4,184 Points

Thank you! This worked.

Hope this helps!

while counter < numbers.count { // counter is less than numbers.count

    sum += numbers[counter] // Get value at current index and add it to the sum

    counter += 1
}

Gary, some while ago I tried your version and found that the challenge editor wouldn't accept counter += 1, but instead insisted on counter++. I left a comment in the review at the time but I'm not sure Treehouse ever looks at such feedback. I just tried it again, and no change: counter += 1 is still being rejected!

@pasan

Hey jcorum ,

I didn't try it in the TreeHouse editor, but they should fix that!

  • thanks
Steven Beckham
Steven Beckham
2,010 Points

This will become important because ++ is being deprecated in Swift 3.0 and must be replaced by += 1. Xcode will already present a caution and recommend avoiding ++.