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

Gregory Rankel
Gregory Rankel
419 Points

2nd task objective

Not sure how to solve the second task of this objective. I tried computing the sum in myplayground and was able to get it to compile however, I think I'm using the wrong logic. Any advice would be great.

Thanks

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

// Enter your code below

while sum < numbers.count {
    print(numbers[sum])
    sum++

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Gregory,

You seem to have got just a bit off track here. The second task wants you to just increment the sum with the value of the array position during that iteration. So every time the loop runs, it pulls the next value in the array, and this value needs to be added to the sum of the previous ones.

So first off, you need to get rid of the print statement (the challenge doesn't want anything printed).

Second, instead of using sum for the loop, you will need to use counter as it was for the first task, and then increment the counter by 1 after each iteration instead of the sum.

Then, we are going to do some math. with the variable sum we are going to add the array number to the previous value of the sum variable. Which would look something like newValue = oldValue + newNumber.

Below is the complete code for Task 2. Have and look and let me know if it makes sense.

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

Keep Coding! :) :dizzy:

Gregory Rankel
Gregory Rankel
419 Points

Jason,

Thank you for the reply and helping me with this objective. I do understand how you explained it and it makes sense. I think I confused myself with how this objective was worded. I'm a newbie, so I think I was making this task harder than what it should be. I have a lot to learn :)

Thanks for taking the time to explain this to me.