Maximum and minimum number from array
let array: [Int] = [4, 8, 2, 6, 9]
var max = array[0]
var min = array[0]
for i in 0..<array.count {
if array[i] > max {
max = array[I]
}
if array[i] < min {
min = array[I]
}
}
print("Max number: \(max)")
print("Min number: \(min)")
Find target number: Example1
func searchNumber(_ array: [Int], _ target: Int) -> Int {
for (index, value) in array.enumerated() {
if value == target {
return value
}
}
return -1
}
let array: [Int] = [4, 8, 2, 6, 9]
let target = 6
print(searchNumber(array, target))
// Output: 6
Find target number: Example2
let array: [Int] = [4, 8, 2, 6, 9]
let target = 6
for i in 0..<array.count {
if array[i] == target {
print("Found \(target) at index \(i)")
}
}
// Output: Found 6 at index 3
✅ Swift: Find Two Numbers That Sum to a Target
Input:
An array of integers
A target sum value
Output:
true if any two numbers sum to the target, else false
Using a Set (Efficient O(n) Solution)
func hasTargetSum(_ nums: [Int], _ target: Int) -> Bool {
var seen = Set<Int>()
for num in nums {
let complement = target - num
if seen.contains(complement) {
return true
}
seen.insert(num)
}
return false
}
// Example usage:
let numbers = [2, 7, 11, 15]
let target = 9
print(hasTargetSum(numbers, target)) // Output: true (2 + 7)
🔹 Explanation:
For each number, calculate its complement: target - num.
Check if the complement is already in the set.
If yes, we found a pair. Otherwise, add the number to the set and continue.
Using loop
let numbers = [2, 7, 11, 15]
let target = 9
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if numbers[i] + numbers[j] == target {
print("(\(numbers[i]), \(numbers[j]))")
}
}
}
✅ Swift Program: Find Second Largest Element
func secondLargest(in numbers: [Int]) -> Int? {
guard numbers.count >= 2 else { return nil }
var first = Int.min
var second = Int.min
for num in numbers {
if num > first {
second = first
first = num
} else if num > second && num != first {
second = num
}
}
return second == Int.min ? nil : second
}
// Example usage
let nums = [12, 35, 1, 10, 34, 1]
if let result = secondLargest(in: nums) {
print("Second largest number: \(result)")
} else {
print("No second largest number found.")
}
Top comments (0)