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

Stuck in a code challenge (again)...

Hi there!

I'm stuck yet again to the same topic but different code challenge:

https://teamtreehouse.com/library/swift-3-collections-and-control-flow/control-flow-with-loops/working-with-loops

I got the first task right. I set the while loop up. Which is:

while counter < numbers.count { counter += 1 }

But task 2 is pretty difficult (for a beginner like me). How do I compute for the sum of all of the values in the array? I understand the question, I just can't seem to translate it into code.

Thanks in advance!

1 Answer

Chirag Jadhwani
Chirag Jadhwani
4,579 Points

Hi!

Here's the correct code and explanation.

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 }

So here, we have the variable counter which increments by the value 1 (counter+= 1). As the while loop moves further and performs the task, counters value increases by 1.

The counter works as the index position in the array numbers. For example array[3], here 3 is the index position and retrieves the value from the position.

Like, the index position 0 in our array numbers has the value of 2.

The sum is calculated by sum = sum + numbers[counter] where initially the sum is 0. So if you form a data table..

counter numbers[counter] sum

//0 is the initial value of sum + numbers[0] is 2 and then the value is stored in sum.

0 2 0+2 = 2
1 8 2+8 = 10 2 1 10+1 = 11 //0 is the initial value of sum + numbers[counter] is 2 and then stored in Sum. and so on... I would suggest you form such data tables. They're very useful.

Thanks man! Appreciate the help. This is very useful indeed!