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

Jared Baumer
Jared Baumer
4,235 Points

I am not sure how to complete this code challenge.

I am stuck on this code chellenge. I completed the objective before but do not think that what I coded is even write for what it was asking. If someone can help me complete this challenge and then explain why it is what it is that would be very helpful.

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

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

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Let me post the working code and go through it step by step.

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

// Loop as long as the counter is less than the number of elements
// in the array. Less than, as indices of arrays are zero based.
// Therefore, indices are 0 to 6 with this array, count returns 7
while counter < numbers.count    {

  // numbers[counter] accesses the first element of the array with the
  // first iteration. That would be numbers[0], numbers[1], numbers[2] etc.
  // As we increment counter with every iteration, we can use it to access
  // each element of the array, one after another.

  // With every iteration, we add the Int we get from the array to the sum
  sum += numbers[counter]

  // Increment the counter at the end of the loop
  // Note that this is deprecated as of Swift 2
  // and should now be counter += 1, just as we
  // increment the sum
  counter++
}

Hope that helps :)