Swift Program to Find Smallest Array Element

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write swift program to find minimum array element.

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 smallest array element we compare all the elements with each other using <operator and get the smallest one.

Below is a demonstration of the same −

Suppose our given input is −

Myarray = [34, 23, 56, 78, 2, 665]

The desired output would be −

Smallest element = 2

Algorithm

Following is the algorithm −

  • Step 1 − Create a function which takes an array as a parameter.

  • Step 2 − Declare a variable named as minval to store the smallest element.

  • Step 3 − Initially assign minval with first element to start the comparison.

  • Step 4 − Use for loop to traverse the given array from second element till the last element.

    Compare the current array element with the minval

    If the current element is less than minval, then replace the value of minval with current element.

  • Step 5 − Create an array of integer type with value.

  • Step 6 − Call the function and pass the array into it as an argument.

  • Step 7 − Print the output

Example

The following program shows how to find smallest array element.

import Foundation import Glibc // Function to find the smallest element func findMinItem(mArr:[Int]) -> Int{ var minval = mArr[0] for j in 1..<mArr.count{ if (mArr[j] < minval){ minval = mArr[j] } } return minval } var arr = [34, 4, 54, 1] print("Array:", arr) print("Smallest element:", findMinItem(mArr: arr))

Output

Array: [34, 4, 54, 1]
Smallest element: 1

Here, in the above code, we have an array = [34, 4, 54, 1]. Now we pass this array into the function named findMinItem() to find the smallest element of the array. So the working of the above code is −

var minval = mArr[0] = 34

1st iteration −

if (4 < 34) // true{ maxval = mArr[j] = 4 }

2nd iteration

if (54 < 4) // false{ maxval = mArr[j] }

3rd iteration:

if (1 > 4) // true{ maxval = 1 }

Return 1. So the smallest element is 1.

raja
Updated on 11-Oct-2022 12:16:08

Advertisements