iOS Swift Collections and Control Flow Control Flow With Loops Working With Loops

Philip Gray
Philip Gray
3,327 Points

Code Challenge Help

I'm absolutely stumped and can't seem to understand what I'm doing wrong.

The question asks:

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.

I believe my code is attached at the bottom, but why doesn't it work out?

My thoughts were that newValue would equal to the counter's corresponding value in the index. I might be throwing around the wrong terminology here and I apologize.

For example, if the counter was 0, then numbers[counter] would be 2?

From there you add sum (0) with new value which is equal to numbers[counter] or 2. Then it would add one to counter, and repeat.

numbers[counter] or numbers[1] = 8 Add that to the sum which is currently 2 and go on.

I'd appreciate any help!

Thanks in advance, Philip

let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0
var newValue = numbers[counter]
// Enter your code below

while counter > numbers.count { 
  sum += newValue
  counter += 1  

1 Answer

54,333 Points

From the instructions: The while loop should continue as long as the value of counter is less than the number of items in the array

Also to get the current value, this line:

var newValue = numbers[counter]

should be inside the loop

Philip Gray
Philip Gray
3,327 Points

oof, I can't believe I didn't see that sooner!

Thank you Kris!