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 Collections and Control Flow Control Flow With Loops Working With Loops

While Loops Code Challenge

I dont’t understand how to solve the second part of the while loop code Challenge

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

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

1 Answer

Matthew Long
Matthew Long
28,407 Points

Looks like the way the challenge was worded has thrown you off. That sum += newValue bit was only meant as an example. That's not a solution.

You want to add each number from the numbers array using the counter as the index. So numbers[0] (when the counter is 0) would be the first value in the numbers array, 2. This is when you add it to the sum variable using that sum += newValue demonstration in the challenge description. It would look like sum += numbers[counter] in this case.

Also, make sure to have the counter incrementing afterward because you would be skipping over the first index value if not.

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

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