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

Zachary Berling
Zachary Berling
10,703 Points

Spent a lot of time on this can't seem to make this code work for challenge.

So far this is what Im able to come up with. I've gotten the loop to generate numbers sequentially up to 42 times I can't seem to get it to compute the sum though. I've used the addition operator sum += newValue as suggested as well as the .count. I feel rather bad at this and quite can't figure this out. I've ran the code several different ways this has been my best attempt so far at generating values other than the ones from the numbers array and or true or false statements.

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

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

repeat { print(counter) counter++ } while counter < sum

Any help would be greatly appreciated. I know I'm going to kick myself after I figure it out. Im probably making it harder than it really is. Thank you in advance

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

// Enter your code below

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

repeat {
    print(counter)
    counter++
} while counter < sum

1 Answer

Jhoan Arango
Jhoan Arango
14,575 Points

Hello :

hopefully my code can help you understand the process a bit.

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

while counter < numbers.count {
var number = numbers[counter] // Using the counter as index for the array
sum += number // adding each number into sum
counter++

}

If you need more help, let me know.

Good luck

Zachary Berling
Zachary Berling
10,703 Points

Thank you very much its interesting I was thinking that the sum += number was suppose to incorporate .count operator. I had no idea that I could incorporate a variable inside the loop to index number = numbers[counter]. One of my revisions did incorporate numbers[counter] but I could not make the script run right. Very insightful thank you again!