// Define an array of integers
var inputArray: [Int] = [1, 3, 8, 9, 2, 0]
// Initialize variables to store largest and second largest elements
var largestElement: Int = inputArray[0]
var secondLargestElement: Int = largestElement
// Initialize variables to store smallest and second smallest elements
var smallestElement: Int = inputArray[0]
var secondSmallestElement: Int = smallestElement
// Find largest and second largest number from array in Swift
for (index, object) in inputArray.enumerated() {
// Check if current element is greater than the largestElement
if object > largestElement {
// Update secondLargestElement to previous largestElement
secondLargestElement = largestElement
// Update largestElement to current object
largestElement = object
} else if object < largestElement && object > secondLargestElement {
// Update secondLargestElement if current object is between largest and second largest
secondLargestElement = object
}
}
// Find smallest and second smallest number from array in Swift
for (index, object) in inputArray.enumerated() {
// Check if current element is smaller than the smallestElement
if object < smallestElement {
// Update secondSmallestElement to previous smallestElement
secondSmallestElement = smallestElement
// Update smallestElement to current object
smallestElement = object
} else if object > smallestElement && object < secondSmallestElement {
// Update secondSmallestElement if current object is between smallest and second smallest
secondSmallestElement = object
}
}
// Print the results
print("Largest element: \(largestElement)")
print("Second largest element: \(secondLargestElement)")
print("Smallest element: \(smallestElement)")
print("Second smallest element: \(secondSmallestElement)")
Comments Explanation:
- Initialization of Variables:
inputArray
: Contains the array of integers.
largestElement
, secondLargestElement
: Variables to store the largest and second largest elements initialized with the first element of inputArray
.
smallestElement
, secondSmallestElement
: Variables to store the smallest and second smallest elements initialized with the first element of inputArray
.
- Finding Largest and Second Largest:
- Loop through
inputArray
using enumerated()
to get both index and object.
- Check if
object
is greater than largestElement
. If true, update secondLargestElement
and largestElement
.
- If
object
is not greater than largestElement
but is greater than secondLargestElement
, update secondLargestElement
.
- Finding Smallest and Second Smallest:
- Another loop through
inputArray
to find the smallest and second smallest elements.
- Check if
object
is smaller than smallestElement
. If true, update secondSmallestElement
and smallestElement
.
- If
object
is not smaller than smallestElement
but is smaller than secondSmallestElement
, update secondSmallestElement
.
- Printing Results:
- Finally, print the values of
largestElement
, secondLargestElement
, smallestElement
, and secondSmallestElement
.