w3resource

Swift Array Programming Exercises: Check if 5 appears as either the first or last element in a given array of integers

Swift Array Programming: Exercise-1 with Solution

Write a Swift program to check if 5 appears as either the first or last element in a given array of integers. The array length should be 1 or more.

Pictorial Presentation:

Swift Array Programming Exercises: Check if 5 appears as either the first or last element in a given array of integers

Sample Solution:

Swift Code:

func first_last_5( _ arra:[Int]) -> Bool {
    if arra.first == 5 || arra.last == 5 
    {
        return true
    } 
    else 
    {
        return false
    }
}
 print(first_last_5([1, 2, 5]))
print(first_last_5([5, 1, 2, 3, 4]))
print(first_last_5([5, 6, 1, 2, 5]))
print(first_last_5([1, 2, 6, 5, 3, 7]))

Sample Output:

true
true
true
false

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Swift Array Exercises.
Next: Write a Swift program to check whether the first element and the last element of a given array of integers are equal.

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://www.w3resource.com/swift-programming-exercises/array/swift-array-exercise-1.php