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

Mohammed Abushamala
Mohammed Abushamala
3,650 Points

Can someone tell me why is this wrong for While loop? why is the equal sign in the while condition is 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 += numbers[counter] print(sum) counter += 1 }

1 Answer

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

Hi there! A good percentage of programming languages out there have what we call "0 indexed arrays" and this means that they start counting at 0. Your counter also starts at 0, which is handy. But the count method counts like humans. It's looking at that array and counting the number of items there. In this example, there are 7 numbers in the array. So your while loop will go while count is less than or equal to 7. At the last iteration, it will try to access the array at index 7. We have 2 at index 0, 8 at index 1... etc. If you count up, you'll see that the last possible number is at array index 6. When it tries to access index 7, it will produce an error as that is outside the bounds of the current array. So what you want to do is count upwards from 0 while counter is less than the count of the array.

Hope this helps! :sparkles: