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

Sum of array in while loop

Hi guys! I tried different kinds of code for this one. Also researched arrays and loops outside treehouse, but nothing worked.

I tried for in loop but the test needs me to use while loop.

Thanks in advance. :)

loops.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
}

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

      }

2 Answers

andren
andren
28,558 Points

For this task you need to pull out the first item from the numbers array during the fist loop, the second during the second loop and so on. To pull out an item from an array you simply need to use brackets where you insert the index of the item you want to pull out. So numbers[0] would pull out the first item, numbers[1] the second item and so on.

Since you need to pull out a different item during each loop you need a number that starts at 0 and increases each time the loop runs, which you already have in the counter variable you use to count the number of loops.

If you use counter to pull out items like this:

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

// Enter your code below
while counter < numbers.count {
    sum += numbers[counter]
    counter += 1
}

Then you will pull out each item from the numbers array as the loop runs, and will end up solving the challenge.

Hi Andren, thank you. I tried your code and played around with other codes too, but it still says

"Bummer! Make sure your condition allows for iteration over all elements in the numbers array and check your calculation of sum!"

andren
andren
28,558 Points

That's strange, I tested the code before I posted it and the challenge passed the code without an issue. Maybe you can try to restart the task using the restart button and then copy and paste the code from my post. The challenges can sometimes bug out a bit but doing that usually fixes it.

Ok! Thank you so much!