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

Joel Duarte
PLUS
Joel Duarte
Courses Plus Student 495 Points

stuck

stuck on sum= sum + newValue

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
}
let index = 0 
Jeroen de Vrind
Jeroen de Vrind
29,772 Points

You were almost there! You only needed to add the specific numbers to the sum variable. Something 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
}
Donald Zarraonandia
Donald Zarraonandia
4,434 Points

So close!

In my opinion you did the hard part. Your while loop is going to run 7 times.

because numbers.count will return the total count of the array which is 7.

The first iteration through the loop counter will be 0, second it will be 1, and so on until 6.

What you want to do is use the counter number as an index number when you reference the array.

To solve this challenge it would be: 2+8+1 etc. Or numbers[0] + number[1] ....+ numbers[6] (Index numbers start at 0 in arrays, so an array of count 7 will have the last index number at position 6.

So what you can do it take the var sum and set it equal to itself plus numbers[counter]. Than you will want to run counter+= 1

so in the while loop it will look like:

sum = numbers[counter] + sum counter += 1

the first iteration will look like this in numbers:

sum now is equal to = numbers[0] + 0 -note numbers[0] takes the first number of the array of 2 -note 0 is what sum currently is

the second iteration will look like this:

sum is now equal to = numbers[1] + 2

1 Answer

Chris Miller
Chris Miller
2,186 Points

Thank you for your help.