w3resource

Swift Array Programming Exercises: Compute the sum of the first 2 elements of a given array of integers. Return 0 if the length of the given array is 0 and return the first element value If the array length is less than 2

Swift Array Programming: Exercise-8 with Solution

Write a Swift program to compute the sum of the first 2 elements of a given array of integers. Return 0 if the length of the given array is 0 and return the first element value If the array length is less than 2.

Pictorial Presentation:

Swift Array Programming Exercises: Compute the sum of the first 2 elements of a given array of integers. Return 0 if the length of the given array is  0 and return the first element value If the array length is less than 2

Sample Solution:

Swift Code:

func array_sum2(_ a: [Int]) -> Int {
    let size = a.count
     if size>1
       {
         return a[0] + a[1]
       }
     else
       {
           return a[0]
       }
}

print(array_sum2([1, 2, 3]))
print(array_sum2([1, 1]))
print(array_sum2([10]))

Sample Output:

3
2
10

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to find the larger value of a given array of integers and set all the other elements with that value. Return the changed array.
Next: Write a Swift program to create a new array of length 2 containing the middle elements from two give array of integers and length 3.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/swift-programming-exercises/array/swift-array-exercise-8.php