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

Help with task 2

I don't understand how to do the second task can someone please share what the answer is supposed to look like, to help me understand why. Since I can't figure it out the way it wants me to find sum I just did it a different way that takes longer but clearly is not the right way. Someone please explain how to solve this second task. Much appriciated! and if you can post a photo of the correct code that would help a lot.

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 = number[0] + number[1] + number[2] + number[3] + number[4] + number[5] + number[6]

1 Answer

Rares Conea
PLUS
Rares Conea
Courses Plus Student 15,000 Points

Hi,

You can say that you find the sum in another way but not an efficient one. If let numbers would have 1000 numbers stored in then you would need to write a lot of code. Make use of the counter variable to acces every position in numbers, retrieve the value that s stored there and add it to sum:

You can do that this way:

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

Let the increment of counter to be the last because you must start from position 0 in numbers.

Thank you so much! that makes a lot more sense. I really appreciate the help.