We can get the length of an array using the .size property like this:
val ourArray = intArrayOf(50, 40, 30)
// Printing the length:
println(ourArray.size) // Output: 3
Using the length
We can use the length to access items from the end of an array.
Because arrays are 0-indexed, the index of the last item is size - 1:
val ourArray = intArrayOf(50, 40, 30)
// Printing the last item:
println(ourArray[ourArray.size - 1]) // Output: 30
// Printing the second to last item:
println(ourArray[ourArray.size - 2]) // Output: 40
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
