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 Collections and Control Flow Control Flow With Loops Working With Loops

Now that we have the while loop set up, it's time to compute the sum! Using the value of counter as an index value,

I have spent a couple of hours on this exercise. What am I overlooking

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

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

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Anthony,

The beginning of the while loop is fine, but the "inside" is where there are some issues.

  • First, the math part needs to come before the increment of the counter.
  • Next, the math is not adding the correct values. Right now, the sum is just being added to the counter with each iteration. But the challenge wants the value at the index in the array for a particular iteration to be added to the sum. It will be like a running total. The first time around will be 0 + 2 to equal 2. The second iteration should be 2 + 8 to equal 10, and so on. To achieve this, you will use the counter as the index value for numbers. To drop a hint for you, you will need to use numbers[counter] in the math part of the loop.

Give it another go with this in mind. If you're still stuck, just leave a comment here.

Keep Coding! :) :dizzy: