Retrieve each value from array and add them together, code cannot iterate over whole array?

JuanB457 Source

For a code question: What it wants is for you to make a for loop that will run down the length of the array it provides. We're going to keep track of where we are in the array with our counter variable. At the end, we should have the sum of all the numbers in that array.

I don't understand why my 2nd loop cannot iterate over the whole array, also how do I check the sum, would that just be printing the sum?

let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0

while sum < numbers.count {
    sum += 1

while counter < numbers.count {
  sum = sum + numbers[counter] 
  counter += 1              


answered 2 years ago Westside #1

If all you want is the sum of all the numbers in the array then you can do this...

let numbers = [2,8,1,16,4,3,9]
var sum = 0

for number in numbers {
    sum += number

print (sum)

or even easier...

sum = numbers.reduce(0, combine: +)

answered 2 years ago Harshit Gupta #2

Strictly following the question statement, I would say the following code will be better option

let numbers = [2, 8, 1, 16, 4, 3, 9]
var sum = 0

for counter in 0 ..< numbers.count {
    sum += numbers[counter]
    print("Counter: \(counter) Sum: \(sum)")

comments powered by Disqus