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

Larry Taylor Jr
Larry Taylor Jr
4,869 Points

Understanding why this is the solution

OK so for this challenge I got this solution that allowed me to pass but I need a little more breakdown on why it was the solution.

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

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

// Enter your code below

1 Answer

andren
andren
28,558 Points

The challenge asks you to compute the sum of the numbers in the array, to get sum of the numbers you simply need to add all of them together. And that is what the code does.

          while counter < numbers.count

Here you are saying that the loop should go while the counter variable is less than the number of items in the numbers array, which results in the loop running once for every number, due to the counter starting at 0.

          sum += numbers[counter]

Here you are taking the sum variable and adding one of the numbers from the number array to it, the first time though the loop the first number from the array will be added, the second time though the second number and so on, this is due to the fact that you are using the counter variable as the index for the array.

          counter++

Then finally you are adding one to the counter, this is needed both to ensure that the loop eventually ends and so that during the next loop you will get the next number out of the numbers array.

At the end of the loop the sum array will be equal to all of the numbers of the numbers array added together, which is what a sum is.

Larry Taylor Jr
Larry Taylor Jr
4,869 Points

Thank you so much andren. I know what I was doing but just needed a further breakdown of exactly how it worked and executes the way it does. You definitely broke it down and allowed me to understand it better