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

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
231,198 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
}