w3resource

Swift Array Programming Exercises: Compute the sum of the values of two given array of integers and each length 2. Find the array which has the largest sum and return the first array if the sum of two given arrays are equal

Swift Array Programming: Exercise-16 with Solution

Write a Swift program to compute the sum of the values of two given array of integers and each length 2. Find the array which has the largest sum and return the first array if the sum of two given arrays are equal.

Pictorial Presentation:

Swift Array Programming Exercises: Compute the sum of the values of two given array of integers and each length 2. Find the array which has the largest sum and return the first array if the sum of two given arrays are equal

Sample Solution:

Swift Code:

func bigger_array(_ a: [Int], _ b: [Int]) -> [Int] {
    if (a[0] + a[1]) >= (b[0] + b[1]) 
    {
        return a
    } 
    else 
    {
        return b
    }
 }
print(bigger_array([1, 2], [3, -4])) 
print(bigger_array([0, 1], [1, 2])) 
print(bigger_array([6, 2], [4, 4]))  

Sample Output:

[1, 2]
[1, 2]
[6, 2]

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to check if two given arrays of integers have 0 as their first element.
Next:Write a Swift program to create an array of length 2 containing the middle two elements from a given array of integers and even length 2 or more.

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-16.php