A
A
Artur Urbanovich2021-04-10 02:19:17
Arrays
Artur Urbanovich, 2021-04-10 02:19:17

Swift. How to find min and max in an array using a loop?

I started training, I'm still bad at thinking.
The task sounds like this:
Using the loop, find the minimum and maximum number.

The array itself:
var numbers: [Int] = [1, 2, 3]
numbers.append(4)
numbers.remove(at: 1)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
briahas, 2021-04-10
@briahas

Sorry, but this is a "school" program. They don't decide "homework" for others here. It helps to understand what is not clear.
Show what you did and what didn't work, and we'll help you figure out why it didn't work.

R
Roman Kerimov, 2021-04-19
@RomanKerimov

import Foundation

let numbers = [5, 1, 6, 2, 4, 3]
print(numbers.min) // 1
print(numbers.max) // 6

In general, the cycle is not needed here.
But if you really want a loop:
var minNumber: Int = 0
var maxNumber: Int = 0

for number in numbers {
    if number < minNumber {
        minNumber = number
    }
    else if maxNumber < number {
        maxNumber = number
    }
}

print(minNumber) // 1
print(maxNumber) // 6

Or:
var minNumber: Int = 0
var maxNumber: Int = 0

numbers.forEach { number in
    if number < minNumber {
        minNumber = number
    }
    else if maxNumber < number {
        maxNumber = number
    }
}

print(minNumber) // 1
print(maxNumber) // 6

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question