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

Raphael Reiter
Raphael Reiter
6,820 Points

compute inside loop

I don't understand how to compute inside my loop...

I got this far in the challenge:

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

// Enter your code below while sum <= 7 { print(sum) sum++ }

thanks for your help

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

// Enter your code below
while sum <= 7 { print(sum)
                sum++
}

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

A few things:

1) you're using sum where you should be using counter. The purpose of the variable counter is to count how many times you've been around the loop.

2) You should stop your loop when counter is less than or equal to 6, or less than 7. The way it is right now you're going to do the loop too many times, which will end up with an error because you'll be going past the end of your array.

3) Inside the curly braces of your loop, before you increment your counter up, you should put sum += numbers[counter]. This is going to use the counter variable as the index of the array, starting with 0, and it will add each item in numbers into sum as it goes through the loop.

Here's the code:

while counter <= 6 {
    sum += numbers[counter]
    counter++
}