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 trialDerek Khanna
603 PointsNot sure how to write this while clause
Don't get how to do this.
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
sum == numbers.count
while counter < sum { (sum = sum +numbers.value)
counter++
}
3 Answers
Ibrahim M.
11,797 PointsOk, the code below is what you are looking for, and just a few points to clarify what's happening:
- Counter starts at 0. It's the index we will use to access items inside the numbers array.
- numbers.count returns the number of items/numbers inside the numbers array, in our case it would return 7 as we have 7 numbers inside the array.
- numbers[counter] returns the number in the array at index 'counter'. That index starts at 0. ex: numbers[0] = 2, numbers[1] = 8, etc... numbers[6] = 9
- So we make a while loop, that has a condition where the counter we use should go through the number of items/numbers inside the "numbers" array.
- The summation is taking the previous sum and adding in the new value found in the array (see #3)
- We then increment the counter by 1, to go to the next index position in the array.
- When the 'counter' value equals numbers.count, the loop ends immediately.
- We use less than (< strictly) and not less than or equal (<=) because array indexes start at 0.
// Enter your code below
while (counter < numbers.count) {
sum = sum + numbers[counter]
counter += 1
}
// Print out the result: should be 43
print(sum)
Derek Khanna
603 PointsWhen I tried, it still didn't work:
let numbers = [2,8,1,16,4,3,9] var sum = 0 var counter = 0
// Enter your code below
while (counter < numbers.count) { sum = sum + numbers[counter] counter += 1 }
print(sum)
priya x
866 PointsThe above code is right but for some reason it's only recognizing the counter increment counter++. Change counter+=1 to the increment operator and it works.