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 trialSam Belcher
3,719 PointsHelp with loops (specifically while loops)
Extremely confused
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
repeat {
sum.append( (numbers[1...7]))
} while counter < numbers.count
1 Answer
Joe Beltramo
Courses Plus Student 22,191 PointsIn the code you provided, there are a few things that are happening here that might be causing you a problem.
As with almost all loops, they generally need a finite destination on knowing when to end the loop, otherwise they will run indefinitely.
In the challenge, they are looking for you to get the sum of all the numbers within the numbers
array by using a while loop. Instead of appending items, try adding them with counter
as your array index.
This means, you must also increment the counter within the loop
. Since your counter will be consecutively growing, it will give the while expression a chance to finish and reach an end.
while counter < numbers.count
One problem you may have using a repeat...while loop though is that it will continue until counter is not less than the size of the numbers
array. So if you want to still use the repeat...while loop, you will need to have your counter stop at 1 less than the size of the numbers
array. i.e. numbers.count - 1 (Otherwise you will get an out of bounds error against your array)
Hope that helps!
Joe Beltramo
Courses Plus Student 22,191 PointsErr, ignore the numbers.count - 1. I miscalculated.
Harold Davis
Courses Plus Student 14,604 PointsHarold Davis
Courses Plus Student 14,604 PointsNot repeating while at the moment we are just setting the while loop and saying while the counter is less than the count add each number together.
you increment the counter by 1 after every iteration by using counter +=1