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

Challenge Task 2 of 2..

I'm at a lose for the second part of this challenge, any insight as to how this should work would be wonderful.

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

while sum < numbers.count {
    print(numbers[sum])
    sum++
}

1 Answer

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

You're getting there.

The goal of this challenge is to calculate the sum of all the numbers in the numbers array, so you don't need to print anything. The way you've structured your while loop, you're printing each element of the numbers array, which isn't the goal.

Firstly, you should be using counter for your condition, not sum. sum is the variable that's going to store the sum of all the integers in the numbers array, so you can't use it as a counter. So, in your code, you should get rid of the print statement, and replace sum with counter.

while counter < numbers.count {

    counter++
}

At this point, you have a while loop that runs 7 times, or as many times as there are numbers in the numbers array. You also have a counter that goes through the numbers 0 to 6 (the indexes of the numbers array) before breaking out of the while loop.

The challenge also gives you a hint: to calculate the sum of all the elements in the array, you need to use one of the following lines in the while loop:

sum = sum + newValue
sum += newValue

What should newValue be so that after the while loop has run its course, sum is equal to the sum of all the elements in the array?