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 trial
samarth sharma
1,758 Pointsstuck at while loops
Now that we have the while loop set up, it's time to compute the sum! Using the value of counter as an index value, retrieve each value from the array and add it to the value of sum.
For example: sum = sum + newValue. Or you could use the compound addition operator sum += newValue where newValue is the value retrieved from the array.
this was my code:
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
while counter < numbers.count
{
counter++
print(numbers[0...6])
}
var newValue = numbers[counter]
sum += newValue
3 Answers
samarth sharma
1,758 Pointsfigured it out thanks for your reply though..
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
var index = 0
while counter < numbers.count{
print(numbers[counter])
sum += numbers[counter]
counter++
}
print(sum)
Akshat Jain
12,819 PointsThere are several things wrong with your code:
while counter { ... }
Will never terminate because it is always true
print(numbers[0...6])
Is unnecessary
var newValue = numbers[counter]
sum += newValue
Cannot be outside the loop if you want to iterate over the array and you can combine the statements into one as I have done below
let numbers = [2, 8, 1, 16, 4, 3, 9]
var sum = 0
var counter = 0
while counter < numbers.count {
sum += numbers[counter]
counter += 1
}
print(sum)
samarth sharma
1,758 Pointsthanks caleb, will do in future !
i didn't understand the 3 back ticks though
could you elucidate ?
Caleb Kleveter
Treehouse Moderator 37,862 PointsJust above the tab key on the top left side of the key board, there is a key for the tilda (~), and back tick (`).
You can also Google 'back tick key' and there should be some images.
Caleb Kleveter
Treehouse Moderator 37,862 PointsCaleb Kleveter
Treehouse Moderator 37,862 Pointssamarth sharma , I thought I might let you know I marked your answer as best, if you ever have any you answer to yourself like you just did, you should mark it also.
I also formatted the code with 3 back ticks (`) and the name of the language, then the code, then 3 more back ticks.