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

Dominiq Martinez
Dominiq Martinez
1,949 Points

while counter < sum { newValue = numbers[counter] sum = sum + newValue counter += 1 } Why doesn't this work?

I am trying to compute the sum by retrieving the value in the index position of the numbers array but it is not retrieving it with the index value of counter.

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

// Enter your code below

while counter < sum {
 newValue = numbers[counter] 
 sum = sum + newValue
 counter += 1
}

2 Answers

Steven Parker
Steven Parker
200,784 Points

The instructions say that the "loop should continue as long as the value of counter is less than the number of items in the array", but the "sum" does not represent the number of items in the array.

In fact, before the loop starts, both "counter" and "sum" are preset to 0, so the test fails on the first try and the loop contents are never executed.

So you need a different term in the "while" condition to compare "counter" to.

Cory Cromer
Cory Cromer
5,171 Points

You're really close. Right now, your while statement loops for as long as the counter is less than your sum. Both have a starting value of 0. Since 0 is not less than 0, your loop will never begin. Even if you changed the starting value, your sum will always be more than your counter as long as you are dealing with positive numbers. Remember, you want to continue the loop as long as the counter is less than the number of items in the array, not the sum of the array. So you need to compare the counter property with the number of items in the list, not the sum. The number of items in the array can be accessed through the .count function. So, your while loop needs to be written as while counter < numbers.count. The body of your while loop looks great. You could shorten it; however, by getting red of the newValue property and directly insert its assigned value. See below.

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

// Enter your code below

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