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

aj picard
aj picard
1,258 Points

Not sure what they're asking me to do here...

They didn't really teach me how to compute this from the lesson I feel like can someone help?

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

while counter < 6 {
  print("Terminate")
  counter += 1
  sum += counter
}
// Enter your code below

1 Answer

Taylor Smith
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Taylor Smith
iOS Development Techdegree Graduate 14,153 Points

hi aj picard! A couple things. If you want to add up each index of the "numbers" array, you would have to go through each index and add them together. That's actually what the counter is for. Having "counter" start at 0, you're going to use that as your index for your "numbers" array. So, by saying numbers[counter], and then increasing that counter by 1 each time, you're essentially saying: numbers[0], numbers [1], numbers[2], etc. Now, you're going to want to store these numbers in a placeholder variable called newValue:

var newValue = numbers [counter]

then you want to add this to your "sum" variable like this:

sum += newValue

then of course you need to up your counter:

counter += 1

so your completed code should like this:

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

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