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

whats the error

whats the problem in my code

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

// Enter your code below
while counter > 6 {
print(sum)
counter += 0 
} 

sum = 1 + 6
Isaac Hartman
Isaac Hartman
6,167 Points

Hello Ronald, Step 1: Create a while loop. The while loop should continue as long as the value of counter is less than the number of items in the array. (Hint: You can get that number by using the count property)

Instead of writing: while counter > 6 { ...

You would write: while counter < numbers.count {...

Also, you want each iteration of the while loop to add the value to sum and continue. Meaning you want numbers[0] to be added to sum, then numbers[1], then numbers[2], and so on.

To achieve this you would write: sum += numbers[counter]

The final code that works is as follows:

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]
    counter += 1
}
Caleb Kleveter
Caleb Kleveter
Treehouse Moderator 37,862 Points

Hi Ronald,

I know you probably want to advance through the Swift courses. The feeling of completing a course is definitely exhilarating, but maybe you should take some time away from it. Looking at all the posts you have on the forum, you might want to give your mind a break.

Don't get me wrong, there are times when you should post on the community, but maybe you should take some time off to refresh your mind and come back to it latter.

When you do run into an issue that can use help, add the error you are getting to your post. It will help people that are answering your question know what you did wrong,

I wash you the best and hope you figure out your issue!

1 Answer

Chris Stromberg
PLUS
Chris Stromberg
Courses Plus Student 13,389 Points

Check my answer that I provided to you, for this same question that your asked previously.