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

Chris Rouse
Chris Rouse
810 Points

Help understanding the solution in Working with Loops

In this task, we have an array of numbers and we want to compute the sum of its values.

We have a variable ,sum, that will store the value of the sum of numbers from the array.

We also have a variable ,counter, which we will use to track the number of iterations of the while loop.

Step 1: Create a while loop. The while loop should continue as long as the value of counter is less than the number of items in the array. (Hint: You can get that number by using the count property)

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

I found this solution in another thread reply, but I want to understand what's going on, particularly the last two lines of the solution.

I understand what's happening in the first while statement, but I don't fully understand what's going on with the last two. I don't want to keep moving along by just looking up the answers in the forum, because that won't help me learn any of this, but rewatching the video isn't helping me grasp this fully either.

1 Answer

David Bangean
David Bangean
1,531 Points

Hey Chris, pay attention to the operator "+=". Like appending, it adds and assigns. So it's adding and assigning "numbers[counter]" to the variable "sum", as well as "1" to "counter". Without "counter += 1", the loop will forever continue endlessly. It increases var counter by 1 each time the loop is completed. So if say we added a "print("The loop worked")" to the body of the loop, it would print "The loop worked" 7 times because there are 7 integers in the array. But what if we changed "counter += 1" to "counter += 2" ? Well it would print "The loop worked" 4 times because it increases var counter by 2 each time the loop is completed. If you're having trouble understanding things, just play with values in the code and see what results you get.

ps I'm a beginner not far ahead you in this track, with no prior experience to code, so if any more experienced users see any mistakes or have better explanations, feel free to correct me.