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

Gabriel S
Gabriel S
480 Points

am not sure how to retrieve the value of number and add it to sum. A little help please?

Am not sure how to retrieve the value of number and add it to sum. A little help please?

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

}

1 Answer

Dave Harker
PLUS
Dave Harker
Courses Plus Student 15,510 Points

Hi Gabriel,

Just looking at the challenge. We're told that "The while loop should continue as long as the value of counter is less than the number of items in the array."

This can be accomplished with:

while (counter < numbers.count) {

We then need to add each of the numbers in the array to the variable provided 'sum'. We can accomplish this with:

// the counter is going to be in line with the array index, so we can use that to select / reference
// the numbers in the array as we 'count' through it
sum += numbers[counter] 

Now we just need to increment the counter variable so we can move to the next element in the array; like this:

// increment our counter by one and by extension increase the index reference in the numbers array 
// also for the next iteration through the while loop (if there is one)
counter += 1

And, close off the while loop:

}

Done :) I hope that helps you make sense of it. Happy coding,

Dave

Gabriel S
Gabriel S
480 Points

Thank for the quick response Dave! it helps out a lot. I don't think we covered this so far did we? thats why I was a little confused...

should I be worried that I didn't get this question?

Dave Harker
Dave Harker
Courses Plus Student 15,510 Points

Hi Gabriel,

should I be worried that I didn't get this question?

Not at all, just keep at it ... review, review ... and practice, practice, practice :) You'll get there, just keep going.

Dave.