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

what shall i do?

what shall i do?

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

// Enter your code below

2 Answers

First you create a while loop that runs while counter is less than the length of the array:

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

Then you add the value of the array at each index to sum and increment counter.

jon kelson
jon kelson
5,149 Points

sum += numbers[counter]...... Hi jcorum in the video were taught to put a println in the centre . could you help me please and explain the centre part of your solution. sum += numbers[counter] many thanks Jon

sum += numbers[counter] is shorthand for sum = sum + numbers[counter].

numbers[counter] gets the value that is in the element of the numbers array that has the index value of counter. So numbers[0] gets the value at index 0, numbers[1] gets the value at index 1, etc.

When all is said and done, the variable sum will hold the sum of the values in the array, or, in 43.

jon kelson
jon kelson
5,149 Points

Thank you for explaining that jcorum . I just get a bit confused why the tests don't always test you on exactly what you have just learnt in the videos before. I guess it's to make us think a little more and find out these things. Thanks