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 trialJake White
2,108 PointsWhat am I doing wrong?
I can't get the second part of this question.
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
// Enter your code below
while counter < 0 {
print(6)
counter++
}
var index < 0
repeat {
print(numbers)
counter++
} while counter < 0
2 Answers
tytyty
4,974 PointsI hope you're trying these in Swift playgrounds because it helps a lot.
let numbers = [2,8,1,16,4,3,9]
var counter = 0
var sum = 0
// Enter your code below
while counter < numbers.count {
sum += numbers[counter]
counter += 1
}
print(numbers) // [2, 8, 1, 16, 4, 3, 9]
print(counter) // 7
print(sum) // 43
++ is deprecated so you should use += 1
Note: You could also use this later on when you get more comfortable with Swift.
let multiples = [2,8,1,16,4,3,9]
var sum = multiples.reduce(0, combine: +)
print(sum) // 43
reduce just means reduce a collection of elements down to a single value by combining them.
You could also do some neat stuff like this.
let numbersArray = [2,8,1,16,4,3,9]
var runningTotal = 0
for (index, numbers) in numbersArray.enumerate() { // this is now enumerated() in Swift 3
runningTotal += numbersArray[index]
print(runningTotal) // 2, 10, 11, 27, 31, 34, 43
}
Jack Weller
6,404 PointsHey, you want to add the value from the index number "counter" from the array "numbers". We can do this by writing sum += numbers[counter]
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++ }
Jake White
2,108 PointsJake White
2,108 PointsAwesome thank you very much this was very helpful, I really appreciate the help!