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 trialboris said
3,607 PointsI am not getting errors, but the challenge is rejecting my code
The code challenge is saying that I need to gather array values from inside the loop to compute the sum. It seems like my code is gathering values from the array that are also inside the loop. Here is my code:
var number = [2,8,1,16,4,3,9] var sum: Int = 0 var counter = 0
while counter < number.count { counter += 1 //The += operator is just used in an X-code playground, but is changed in the code //challenge. print(sum) sum = counter + number.removeFirst() }
var number = [2,8,1,16,4,3,9]
var sum: Int = 0
var counter = 0
while counter < number.count {
counter++
print(sum)
sum = counter + number.removeFirst()
}
3 Answers
Christian McMullin
13,086 Pointsfirst thing, I don't know how you have it typed into the challenge but they are very particular. In the challenge the array is numbers not number. That alone throws off challenges. Second. since the first index number is 0 you need to have the sum += numbers[counter] first and then increment counter. they way you have it makes so the first sum is calling index 1 instead of 0.
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++
}
Caleb Kleveter
Treehouse Moderator 37,862 PointsOne thing I noticed is that you have number.count
instead of numbers.count
, multiple numbers, not one.
This is the loop I ended up with:
// While the counter is less the the length of the numbers array
while counter < numbers.count {
// Add to the variable sum the number in the numbers array at the index of counter
sum += numbers[counter]
// Increment counter by one
counter++
}
Jennifer Nordell
Treehouse TeacherHi there! I feel like you've misunderstood the instructions of the challenge. First, they don't want you to print anything so you can remove that line. Secondly, they want you to keep a running total of the amounts in the array. They want you to get the sum of all those numbers in that array.
If you need the full solution and explanation, you can find it here: