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

while loop

not to sure what the situation is I looked at my notes

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

// Enter your code below
while numbers <= 6 {print(numbers)numbers+}

You hard coded the condition instead of referencing the array length using numbers.count

So instead of: numbers <= 6 it should be: counter < numbers.count

I'm not familiar with swift but other languages have this task printed out as follows

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

The challenge didn't accept it when one of the counter++ or sum += came first although it is the same result.

1 Answer

Hi Kevin,

You want to set up a loop that continues to loop while your counter is less than the number of elements in the array. At each iteration of this loop you want to add the value of the counter element within the array to the sum variable you initialized to zero.

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++
}

The first three lines are provided for us; that sets everything up nicely. Next, we have a while loop which will keep going while counter remain less than numbers.count. That's the length of the array we were provided with. Within each loop we acces the array, numbers[counter] and add the value that's there to the current value contained in sum.

So, at the end of all the looping, we will have the total value of all the elements of the numbers array contained in the variable, sum.

I hope that makes sense - let me know how you get on.

Steve.