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

Heidi Toft
Heidi Toft
1,894 Points

I am having difficulty getting my number from the array and adding it

I am using while loops and am trying to get a value from an array and add it to get a total sum for all of the numbers in the array.

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

// Enter
while counter < 7 {
  print(counter)
  counter += 1
  }

while counter < numbers.count {
    sum += numbers[counter]
    counter += 1
}

2 Answers

Why are you running with 2 while loops at the same time that affect the same objects?

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

//This will only increment the counter, you should do a repeat here instead of while.
while counter < 7 {
  print(counter)
  counter += 1
  }

ex:
repeat{
counter += 1
print(counter)
sum += numbers[counter]
}while counter < numbers.count
James Gray
James Gray
8,568 Points

I think you're looking for something more like this. In this while loop counter will never exceed the range of the list "numbers" and it and sum will be incremented up each iteration.

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

while counter < numbers.count {
sum += numbers[counter]
counter += 1
}
print(sum)