In this tutorial, you shall learn how to print the contents of a given array in a single line in Kotlin, using For loop, with examples.
Kotlin – Print array in single line
To print an Array in single line in Kotlin, use For Loop. Inside For Loop, write print statement to print the element. If the body of For Loop has only one statement, then it can written right after for-in.
Refer Kotlin For Loop tutorial.
Syntax
The syntax to print elements of array arr
in a single line is
for (x in arr) print("$x ")
Examples
1. Print the given array to output in a single line with space as separator
In the following example, we take an array of integers, and print them to standard output in a single line with space as separator between the elements.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf(2, 4, 6, 8, 10, 12)
for (x in arr) print("$x ")
}
Output
2 4 6 8 10 12
2. Print the given array of strings in a single line
In the following example, we take an array of strings, and print them to standard output in a single line.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry")
for (x in arr) print("$x ")
}
Output
apple banana cherry
Conclusion
In this Kotlin Tutorial, we learned how to print an array in single line using For Loop, with examples.