Initialize an IntArray with 1 to n in Kotlin
This article explores different ways to initialize an IntArray with 1 to n in Kotlin.
1. Using IntArray constructor
A simple solution to initialize an Int array with a range of elements is using the IntArray constructor with an initializer function as a second parameter. This can be implemented as follows in Kotlin:
|
1 2 3 4 5 6 |
fun main() { val n = 10 val array = IntArray(n) { it + 1 } println(array.contentToString()) } |
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2. Using Kotlin Ranges
Another viable alternative is to generate a range of increasing values is using the Kotlin Range. To get an IntArray, we can call the toIntArray() function, as shown below:
|
1 2 3 4 5 6 |
fun main() { val n = 10 val array = (1.. n).toList().toIntArray() println(array.contentToString()) } |
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
To fill an “existing” array with an increasing sequence of numbers, do as follows:
|
1 2 3 4 5 6 7 8 |
fun main() { val n = 10 val array = IntArray(n) (1.. n).forEach { array[it - 1] = it } println(array.contentToString()) } |
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Or, even better:
|
1 2 3 4 5 6 7 8 |
fun main() { val n = 10 val array = IntArray(n) (0 until n).forEach { array[it] = it + 1 } println(array.contentToString()) } |
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3. Using Arrays.setAll() function
Finally, we can use the Arrays.setAll() function to fill the array with sequential integers. It takes the generator function and computes the value for each index, as shown below:
|
1 2 3 4 5 6 7 8 9 |
import java.util.* fun main() { val n = 10 val array = IntArray(n) Arrays.setAll(array) { it + 1 } println(array.contentToString()) } |
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
That’s all about initializing an IntArray with 1 to n in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)