To create a set of numbers from 1 to N in Kotlin, you can use a loop to add each number to the set.
In this example,
numberSet
.add
method.fun main() {
val numberSet = mutableSetOf<Int>()
for (i in 1..5) {
numberSet.add(i)
}
println("Set of numbers from 1 to 5: $numberSet")
}
Set of numbers from 1 to 5: [1, 2, 3, 4, 5]
In this example,
numberSet
.add
method.fun main() {
val numberSet = mutableSetOf<Int>()
for (i in 1..10) {
numberSet.add(i)
}
println("Set of numbers from 1 to 10: $numberSet")
}
Set of numbers from 1 to 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In this tutorial, we learned How to create a Set of Numbers from 1 to N in Kotlin language with well detailed examples.