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 trialSean Lafferty
3,029 PointsThis is impossible
Please help, I jsut cant grasp this stuff :(
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
newValue = numbers.count()
sum = newValue +=1
}
1 Answer
Jennifer Nordell
Treehouse TeacherHi there! I see that you've been trying so let's take a look at the solution step by step. It's not impossible!
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
}
Ok so we set up our while loop, which you did correctly as it passed step 1. There must be some confusion about the next step. We have a sum
variable which is started at 0. This makes sense as we haven't yet added anything to it. What we're wanting to do is create a running total and keep track of it.
The numbers[counter]
will pull a value from that index of the numbers
array which is already set up for us. Because we start with the counter at 0, the very first iteration will pull the number at the 0 index of the numbers array (which is 2) and add it to our sum. This gives us a value of 2 for the sum. Then we increment the counter which puts it at 1.
The next iteration will pull a value from numbers
at the index of 1, because that is our current value of counter. The number at the index of 1 is 8. It is now added to sum, which gives it a value of 10. This process will repeat until we've gotten every number out of the array and added its value to sum resulting in the sum of all elements of the array.
Hope this clarifies things!
Sean Lafferty
3,029 PointsSean Lafferty
3,029 PointsHero! Thankyou very much!