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

Adrian Yao
Adrian Yao
1,002 Points

What value is new value? Inside the loop?

I am confused by what it whats me to put in "newValue", thanks.

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

// Enter your code below

while counter < 7 {
print("sum")
counter += 1
}

var sum += print ("sum")

1 Answer

Mike Hickman
Mike Hickman
19,817 Points

Hi Adrian,

You did good on step 1. Let's tweak stuff for step 2.

  1. You don't need print in this exercise. Only use print or return when it tells you to print or return.
  2. You never want to have to manually take time to count out the numbers in an array. If it was an array of 100+ items, you'd drive yourself crazy trying to count that all out. So, at the start of your while loop, you want counter < numbers.count instead of 7. That way, if the array gets larger or smaller, you won't have to change the code to start your while loop. It will always read while counter is less than the number of items in the numbers array and that's what you want.
  3. newValue here is just their way of saying the value of whichever number in the array you happen to be on for that single loop. First loop, newValue will be 2 (first number in the array), second will be 8, and so on.
while counter < numbers.count {
 sum += numbers[counter]
 counter += 1
}

The loop step-by-step would be: (starting with counter = 0, sum = 0)

  1. Is the value of counter less than the total number of items in the numbers array?
  2. Yes. Run the loop.
  3. sum += numbers[counter] - sum is 0. We're using counter (which is 0 here) as the index for the array. So, numbers[0] is what that equates to. 0 (sum) + 2 (numbers[0]) = 2
  4. Counter + 1 = 1.
  5. Sum now = 2. Counter now = 1. Loop continues.
  6. 2 (sum) + 8 (numbers[1]) = 10
  7. Count + 1 = 2. Counter now = 2. Sum now = 10.

Good luck,

Mike