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

computing the sum of a while loop

hey so can you please help me out I'm not quite sure how they want me to do this

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(counter)
counter++

}

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

What they want you to do is to move through the array "numbers" one element at a time and store the sum of all those elements. So they want "sum" to eventually equal 2 + 8 + 1 + 16 + 4 + 3 + 9. We can do this with the code below:

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

// Enter your code below

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

Our numbers array sum and counter are started for us. So the counter moves through the indexes of the array one at a time. We then take the number at that index and add it to sum. When the while loop exits the sum will be the grand total of all the elements in the array.

Christopher Augg
Christopher Augg
21,223 Points

Kevin,

Every iteration of the while loop will cause counter to increment until it meets the condition given counter less than numbers.count . The instructions give you an example of the code you need to place where you have print statement. You just need to change that code so that you are accessing the array at the current HINT "counter"

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

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

Trying not to just give you code but please let me know if this is not enough.

Regards,

Chris