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

Gabriel Spranger Rojas
Gabriel Spranger Rojas
7,350 Points

Idk what's wrong

I've done everything that is asked. But I keep getting an error. Please help.

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 - 1 {
  var newValue = numbers[counter]
  sum += newValue
  counter += 1 
}

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! You're so close on this one! The problem here lies in that you're not counting the very last element of the array. This is the line responsible:

while counter < numbers.count - 1

Keep in mind that the numbers array has a count of 7. There are seven items in the array. We want to count from zero to six and then stop. This line says to do this code while counter is less than 6. Given that the last element is in position 6, what happens to this evaluation? When counter reaches 6, then it will not be less than the count - 1 but rather equal to it, and the last iteration for the last item doesn't happen.

But this is easily fixed!

while counter < numbers.count

When the iteration reaches 6, it will still go out and add the number at position numbers[6], which is totally valid. You just need to get rid of the -1 in the opening condition of your while.

Hope this helps! :sparkles:

edited for additional note

In your effort to not go outside the boundaries of the array, you accidentally omitted the last item from the calculations.

Gabriel Spranger Rojas
Gabriel Spranger Rojas
7,350 Points

That was the problem. Thank you very much!