w3resource

Swift Array Programming Exercises: Compute the sum of all the elements of a given an array of integers and length 4

Swift Array Programming: Exercise-4 with Solution

Write a Swift program to compute the sum of all the elements of a given an array of integers and length 4.

Pictorial Presentation:

Swift Array Programming Exercises: Compute  the sum of all the elements of a given an array of integers and length 4

Sample Solution:

Swift Code:

func sum4(_ arra: [Int]) -> Int {
    return arra.reduce(0, +)
}
print(sum4([1, 2, 3, 4]))
print(sum4([1, 5, 7, 11]))
print(sum4([-5, 4, 1, 0]))

Sample Output:

10
24
0

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous:Write a Swift program to test if two given arrays of integers have the same first or last element. Both arrays length must be 1 or more.
Next: Write a Swift program to rotate the elements of an array of integers to left direction.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.