In
my previous post, I explained what is an array and how to define it in kotlin.
In this post, I am going to show,how to print elements of an array.
Print elements of
array using for loop
ArrayUtil.kt
fun main(args: Array<String>) { var arr: Array<Int> = arrayOf(1, 2, 3, 4) for (ele in arr) { println(ele) } }
Output
1 2 3 4
Print array elements
using 'Arrays.toString' method
ArrayUtil.kt
import java.util.Arrays fun main(args: Array<String>) { var arr: Array<Int> = arrayOf(1, 2, 3, 4) println(Arrays.toString(arr)) }
Output
[1, 2, 3, 4]
Print array elements
using array.indices
ArrayUtil.kt
fun main(args: Array<String>) { var arr: Array<Int> = arrayOf(2, 3, 5, 7) for (index in arr.indices) { println(arr[index]) } }
Output
2 3 5 7
Print array elements
using array.withIndex
ArrayUtil.kt
fun main(args: Array<String>) { var arr: Array<Int> = arrayOf(2, 3, 5, 7) for ((index, value) in arr.withIndex()) { println("index : $index, value : $value") } }
Output
index : 0, value : 2 index : 1, value : 3 index : 2, value : 5 index : 3, value : 7
Print array elements
using while loop
ArrayUtil.kt
fun main(args: Array<String>) { var arr: Array<Int> = arrayOf(2, 3, 5, 7) var sizeOfTheArray = arr.size; var index : Int = 0; while(index < sizeOfTheArray){ println("index : $index, value : ${arr[index]}") index++ } }
Output
index : 0, value : 2 index : 1, value : 3 index : 2, value : 5 index : 3, value : 7
No comments:
Post a Comment