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

I need help while loops for swift basics 2.0

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

while sum <= counter{ print(sum + counter) sum++ sum = sum + numbers }

1 Answer

Here you go ..

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

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

Please let me know if you need explanation

Okay, so, [counter] inside the while loop; why is that there, and what is it doing exactly?

counter is doing two jobs: 1- it guides the iterations of the while loop: so while will keep looping as long as counter value is less than the numbers.count which is 7. Once counter is 7 , the looping stops. that's why we increase the counter by 1 inside the loop 2- it acts as an index for the array: We need to sum the values in the array , this means start with first number and each iteration we add the next number to it.. so we start with sum = 0 and then first iteration we add the value in the first location of the array which is numbers[0] , then next iteration we add the next one which is numbers[1] and so on. for this job we use counter the array index : numbers[counter] because counter start with 0 and ends with 6. it perfectly serve the purpose.