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
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