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

john tyler
john tyler
933 Points

what? I'm confused

What did I do wrong here

loops.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 += 1
    sum = sum + numbers[counter]
}

2 Answers

Hans van de Koot
Hans van de Koot
1,278 Points

Hi John, I think because you increment the counter before you add numbers[counter] to sum, the first integer of the array is not considered. Furthermore, because you still increment the counter when numbers.count is reached, numbers[counter] will end up out of bounds. Best--Hans

Wouter Willebrands
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Wouter Willebrands
iOS Development with Swift Techdegree Graduate 13,121 Points

Hi John,

You are actually really close. The problem now is with your logic operator. Keep in mind that arrays start counting at 0. The highest value inside this array is at position 6 instead of 7. You operator now runs the loop until it is equal to numbers.count, although 'count' counts the actual amount of values inside the array, which in this case is 7. Changing the logic operator to include only < should make the code run as you want to.

I hope this solves your problem, if not please don't hesitate to ask. Keep it up!

-WW