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 trialLogan Standard
1,015 PointsChallenge Task 2 - I have the right code
Okay, so this is actually correct, but it was kind of a guess. The reason for this post is to make sure I'm understand what this code is doing. And forgive me, I'm going to break this down one line at a time just to be sure I understand.
let numbers = [2,8,1,16,4,3,9] var sum = 0 var counter = 0
while counter < numbers.count { - This is saying that numbers.count array is less than the counter, correct?
sum += numbers[counter] - This line I guessed :/ but I think it's saying sum is equal to the the numbers in the array?
counter++ - With this, this is adding a +1 to the counter, where the number amount in the array is stored, and added to sum variable, and will continue to go through this loop until counter is greater than the numbers array?
}
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++
}
2 Answers
jcorum
71,830 PointsA few comments:
while counter < numbers.count { - This is saying that numbers.count array is less than the counter, correct?
Not quite. numbers.count returns the size of the numbers array, and the while loop runs as long as counter is less than that count. Perhaps that is what you meant. But you say numbers.count is an array and it isn't. It's an Int.
sum += numbers[counter] - This line I guessed :/ but I think it's saying sum is equal to the the numbers in the array?
Again, not quite. It is saying to give sum the value of sum plus the value of numbers[counter]. This is shorthand for this longer version: sum = sum + numbers[counter]
counter++ - With this, this is adding a +1 to the counter, where the number amount in the array is stored, and added to sum variable, and will continue to go through this loop until counter is greater than the numbers array?
It's just adding 1 to counter, or as some say, it is incrementing counter by 1.
Logan Standard
1,015 PointsI appreciate you responding back.
Thank you