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

Nirav Raichura
Nirav Raichura
1,168 Points

How do we compute the sum from numbers within an array of Ints, using another variable and assigning it the index value?

We have a 'while loop' set up in the code below. The task here is: Using the value of 'counter' as an index value, retrieve each value from the array (numbers) and add it to the value of sum. For example: sum = sum + newValue. Or you could use the compound addition operator sum += newValue where newValue is the value retrieved from the array.

This was one of the questions on the challenge quiz for 'while loop' and I am stuck here since a long time. I will be obliged if someone could help me understand how to get this done.

Thank you.

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

// Enter your code below

while counter < numbers.count {
  counter++
  //////// ?

  sum += sum + counter
  }

2 Answers

Hi Nirav

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

remember += is to add while the = operator is to assign.

Let me know if it helps

Nirav Raichura
Nirav Raichura
1,168 Points

Thank you, Fernando.

That worked perfectly. I see where I was going wrong. Thank you!

Terence Fan
Terence Fan
478 Points

Hi,

Can someone help me with this. I am stuck in this code challenge. I can't seem where I have gotten it wrong.

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

// Enter your code below while counter <= numbers.count {

sum = sum + numbers[counter]
counter += 1

}