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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Haris Periorellis](https://secure.gravatar.com/avatar/10749ddb9dfba41a3261d4ba9fc6464d?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Haris Periorellis
461 PointsWhy is this wronge?
Why is this wronge?
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter < 7 { print (7) 7++ }
2 Answers
![Steve Hunter](https://uploads.teamtreehouse.com/production/profile-photos/806282/micro_Ironman.jpg)
Steve Hunter
57,712 PointsHi Haris,
You want to use the while loop to iterate through each element of the array. At each step, add the element into the variable, sum
.
First, you need to set the limits of the while loop. This is done using counter
; while counter
is less than the number of elements in numbers
you want to loop. Else, you want to stop. Inside the loop, increment counter
using the ++
operator.
Then, access the array by using the counter to point at the current element - you can use square bracket notation to access that element, like numbers[counter]
. Add that value into sum
. Something like:
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++
}
I hope explains the challenge for you.
Steve.
![Roberto Pando](https://secure.gravatar.com/avatar/2f257e5ddefc6f0a1d88cd0c1d79dadd?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Roberto Pando
9,486 PointsFor the condition of the while loop instead of explicitly stating the count of the array you can do just that with the syntax .count, suppose in a real project you decide to add another number then you would have to change the condition as well, therefore .count is the best option. After that you have to increment counter++ otherwise the loop would continue forever because the condition is never going to be met. the correct code looks like this.
while counter < numbers.count {
sum = sum + numbers[counter]
counter++
}