w3resource

Swift Array Programming Exercises: Find the larger value of a given array of integers and set all the other elements with that value


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.

Pictorial Presentation:

Swift Array Programming Exercises: Find the larger value of a given array of integers and set all the other elements with  that value

Sample Solution:

Swift Code:

func newarray(_ arra: [Int]) -> [Int] {
    var new_arra = arra
    
    if new_arra.first! > new_arra.last!
     {
        new_arra[1] = new_arra.first!
        new_arra[2] = new_arra.first!
     } 
    else 
     {
        new_arra[0] = new_arra.last!
        new_arra[1] = new_arra.last!
     }
    return new_arra
}

print(newarray([1, 2, 3]))
print(newarray([-5, -4, 0]))
print(newarray([12, 14, 16]))

Sample Output:

[3, 3, 3]
[0, 0, 0]
[16, 16, 16]

Go to:


PREV : Write a Swift program to create a new array with the elements in reverse order of a given array of integers.
NEXT : 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.

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.