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 2.0 Collections and Control Flow Control Flow With Loops Working with Loops

Jack Colosky
PLUS
Jack Colosky
Courses Plus Student 2,263 Points

While loop is going on forever

The error says that the loop is going on forever. I thought that if the counters value is at 7 then it would stop, what am I doing wrong, please help!

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

// Enter your code below

while counter < numbers.count {
counter += 1
}
Jack Colosky
Jack Colosky
Courses Plus Student 2,263 Points

I found the answer but I don't under stand it, could you please explain this part of the code to me?

print(numbers[sum])

not sure if that is right but can you please explain?

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Jack Colosky,

We have an array of numbers. We want to compute the total (sum) of all of the numbers inside that array. The sum starts out with an initial value of 0. We also have a counter variable with an initial value of 0.

Now we create a while loop. The loop will continue as long as the counter is less than the number of items in the numbers array.

Inside the body of this loop, we compute the sum of the numbers. First we take the previous sum value and then add the value of the number in the array to it. We get the number from the array using subscript syntax. Since arrays are zero based, and our counter starts off with a value of 0, using the counter to subscript the array will return us the first value in the array.

You can think of it like this. sum = sum + numbers[0]

After we perform this math, we increment the value of counter by 1. This loop then runs again, but this time using the value of 1 for the counter to retrieve the number from the array.

This process will continue until the while loop's condition evaluates to false.

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++
}

Good Luck