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 trialMichael Zarucki
803 PointsHow to retrieve value of sum through while loop?
How do I retrieve value of sum through while loop?
isn't the answer : sum == numbers.count ?
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter < numbers.count {
counter += 1
}
1 Answer
David Papandrew
8,386 PointsHi Michael,
numbers.count will give you the number of items in the array. It will not provide you with a sum of the array values unfortunately.
Instead, using the while loop, each time the loop runs, you will grab an item from the array and add it to the sum variable. Also, each time you run the while loop, you will increment the counter variable. Since counter variable starts at 0 and increments through 1, 2, 3, etc., you will use the counter value as your index value when "grabbing" an array value to add to the sum.
Here is the code:
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
}
Hope that helps.
Michael Zarucki
803 PointsMichael Zarucki
803 PointsDavid,
It is still a little confusing, but seeing the answer makes it obvious. I'll probably go back to the loop lessons and review the information.
Thank you,
Michael