Swift Program to Largest Array Element Using Library Function

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write swift program to find largest array element using library function.

An array is an ordered collection which is used to store same type of data. For example, if any array is of integer type then it will only store integers, you are strictly not allowed to store elements of other data types like string, float, etc.

To find the largest array element Swift provide an in-built function named max(). This function return maximum element from the given array. Here the returned object of type Optional. So we type cast the value into the required datatype. This function will return nil if the given array is empty.

Below is a demonstration of the same −

Suppose our given input is −

Myarray = [34, 23, 56, 78, 2, 67, 834, 45, 665]

The desired output would be −

Largest element = 834

Syntax

Following is the syntax −

Arr.max()

Algorithm

Following is the algorithm −

  • Step 1 − Declare an array with value.

  • Step 2 − Find the largest array element using max() function.

var maxElement = myarray.max()!

Here using ! We type cast the returned value into Int.

  • Step 3 − Print the output

Example 1

The following program shows how to find the largest array element using library function.

import Foundation import Glibc var myarray = [34, 434, 23, 9, 5, 39, 87, 92, 823] print("Array:", myarray) // Finding the largest array element var maxElement = myarray.max()! print("Maximum Element:", maxElement)

Output

Array: [34, 434, 23, 9, 5, 39, 87, 92, 823]
Maximum Element: 823

Here, in the above code, we have an array = [34, 434, 23, 9, 5, 39, 87, 92, 823]. Now we find the maximum element from the array using max() −

var maxElement = myarray.max()!

Here using ! We type cast the returned value of max() function into Int because it will return value of Optional Type like −

Array: [34, 434, 23, 9, 5, 39, 87, 92, 823]
Maximum Element: Optional(823)

So after using type cast the final output is −

Array: [34, 434, 23, 9, 5, 39, 87, 92, 823]
Maximum Element: 823

Example 2

The following program shows how to find the largest array element using library function.

import Foundation import Glibc var myarray = ["Bogo", "Aoao", "Wowo", "Qoqo"] print("Array:", myarray) // Finding the largest array element var maxElement = myarray.max() // Here we unwrap the value using let switch maxElement{ case .some(let unwrapped): print("Maximum Element:", unwrapped) case .none: print("Nil") }

Output

Array: ["Bogo", "Aoao", "Wowo", "Qoqo"]
Maximum Element: Wowo

Here, in the above code, we have an array = ["Bogo", "Aoao", "Wowo", "Qoqo"]. Now we find the maximum element from the array using max() −

var maxElement = myarray.max()

Now we unwrap the value using let and the final output is −

Array: [34, 434, 23, 9, 5, 39, 87, 92, 823]
Maximum Element: Optional(823)
raja
Updated on 11-Oct-2022 12:01:15

Advertisements