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 trialAustin Knupp
2,986 PointsLoops Challenge
The wording of the question is throwing me off. I cannot figure out what I am doing wrong. Please help! :)
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter < numbers.count {counter += numbers.count
print(sum = sum + numbers)
}
1 Answer
Matthew Long
28,407 PointsYou set up the while loop correctly, but the code inside the while loop is incorrect.
When the wording of a question doesn't make sense you can usually predict what they are trying to ask for. For example, your counter adds the length (or count) of numbers
each time it is ran. Therefore, it will only run once since counter
must be less than numbers.count
. It would be logical to predict that the challenge wants you to loop over the values in the numbers
array. This would mean you would need to add one to counter
at the end of each loop.
Next, the question never asked you to print anything.
Sometimes the wording for the challenges throw me off too. Especially the iOS courses. The iOS course challenges are especially wordy.
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
while counter < numbers.count {
sum += numbers[counter]
counter += 1
}
Keep up the hard work!
Austin Knupp
2,986 PointsAustin Knupp
2,986 PointsThank you! My only question then is why do we put "counter" in brackets after "sum += numbers" ?
Matthew Long
28,407 PointsMatthew Long
28,407 PointsThe counter in the brackets is the index value of the
numbers
array. The 1st index,0
, of thenumbers
array has a value of2
. So you add2
to thesum
. The second time through the loop the counter is equal to 1. This is the 2nd index of thenumbers
array which means you'll add8
tosum
. All the way untilcounter < numbers.count
.