0

For a code question: What it wants is for you to make a for loop that will run down the length of the array it provides. We're going to keep track of where we are in the array with our counter variable. At the end, we should have the sum of all the numbers in that array.

I don't understand why my 2nd loop cannot iterate over the whole array, also how do I check the sum, would that just be printing the sum?

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

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

while counter < numbers.count {
  sum = sum + numbers[counter] 
  print(numbers[counter])
  counter += 1              
}
2
  • Would you mind pasting the exact code question. It would really help. Commented May 6, 2016 at 15:02
  • I am not sure what you are looking for: however this may point you in the right direction. Your second loop is iterating over the whole array. However your first loop is adding 1 to sum for every element in numbers (aka it is sum is 7 by the time you are done with the first loop) Then your second loop goes through the array and adds each value in that array to sum, so your result of sum is 7 more than it should be. Commented May 6, 2016 at 15:13

2 Answers 2

3

If all you want is the sum of all the numbers in the array then you can do this...

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

for number in numbers {
    sum += number
}

print (sum)

or even easier...

sum = numbers.reduce(0, combine: +)
Sign up to request clarification or add additional context in comments.

2 Comments

did't know what this "sum = numbers.reduce(0, combine: +)" way. swift is awesome
@harshitgupta If you're interested in why it works, it's because reduce takes an initial value, and a function that takes this value, along with the current element of the array as an input – and returns the modified version of the initial value, which is presented again to the function at the next iteration. As this function's signature is (Int, Int) -> Int in this particular case, and the + operator is just a function that can do exactly that, you can pass the + operator straight in. Swift is indeed awesome.
0

Strictly following the question statement, I would say the following code will be better option

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

for counter in 0 ..< numbers.count {
    sum += numbers[counter]
    print("Counter: \(counter) Sum: \(sum)")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.