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 trialHaris 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
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
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++
}