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.

Download Code

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:

Download Code

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.

Download Code

Output:

1 2 3
4 5 6 7
8 9

 
Using foreach loop:

Download Code

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.

Download Code

That’s all about printing two-dimensional arrays in Kotlin.