Print two-dimensional array in Kotlin
This article explores different ways to print two-dimensional arrays in Kotlin.
A two-dimensional array is a single-dimensional array having another single-dimensional array as its elements. You can print it using any of the following methods:
1. Using contentToString() function
You can use the contentToString() function to print string representation of each single-dimensional array in the given two-dimensional array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val arr: Array<IntArray> = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6, 7), intArrayOf(8, 9) ) for (i in arr.indices) { println(arr[i].contentToString()) } } |
Output:
[1, 2, 3]
[4, 5, 6, 7]
[8, 9]
The above code uses an index-based for-loop for printing the 2D array. This can be effectively done using the foreach loop, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val arr: Array<IntArray> = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6, 7), intArrayOf(8, 9) ) for (row in arr) { println(row.contentToString()) } } |
Output:
[1, 2, 3]
[4, 5, 6, 7]
[8, 9]
2. Using nested loops
The custom solution is to use two loops – the outer loop represents the first dimension, and the inner loop represents the second dimension of a two-dimensional array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun main() { val arr: Array<IntArray> = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6, 7), intArrayOf(8, 9) ) for (i in arr.indices) { var j = 0 while (j < arr[i]?.size) { print(arr[i][j].toString() + " ") j++ } println() } } |
Output:
1 2 3
4 5 6 7
8 9
Using foreach loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun main() { val arr: Array<IntArray?> = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6, 7), intArrayOf(8, 9) ) for (row in arr) { if (row != null) { for (col in row) { print("$col ") } } println() } } |
Output:
1 2 3
4 5 6 7
8 9
3. Using contentDeepToString() function
You can also use the contentDeepToString() function to print the string representation of the “deep contents” of an array. For multidimensional arrays, this will print the string representation of each dimension.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val arr: Array<IntArray> = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6, 7), intArrayOf(8, 9) ) println(arr.contentDeepToString()) // [[1, 2, 3], [4, 5, 6, 7], [8, 9]] } |
That’s all about printing two-dimensional arrays 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 :)