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

Anik Devaughn
Anik Devaughn
7,751 Points

Adding values of an array with each other inside a while loop

Hey! Not sure how i should proceed with Challenge Task 2 of 2 in Swift Collections n Control Flow (While Loop challenge).

These are the logical steps I have considered:

  1. The counter stores the number of values contained within the array called numbers
  2. The sum should contain the sum of all the values from the array
  3. The first step that i completed, setup the counter variable in place (which works fine):

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. Now my challenge is to figure out how i can add together each value with the index 0 up to index 6 from the numbers array, by using the counter to define the index value? Basically: sum = numbers[0] + numbers[1] + numbers[2] + ...numbers[6]
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 = counter
    sum = sum + newValue
}

1 Answer

Anik Devaughn
Anik Devaughn
7,751 Points

I figured it out! Noticed that my xcode was bugging for some reason when i tried to insert counter as an index value for numbers. but i sorted it out and now it works! added this within the while loop

var newValue = numbers[counter] //uses counter as an index value for the array
sum += newValue //adds the first value in sum, and keeps adding new values in the loop until number of iterations are done
counter += 1