Kotlin program to reverse an array :
In this kotlin programming tutorial, we will learn how to reverse an array using two different ways : Reverse the array, assign this new array to a different variable and reverse an array in place. We are showing these examples for integer arrays, but you can use them for any other arrays with different data types. Let’s take a look at the programs :
Reverse an array and create one different array :
import java.util.Arrays
fun main(args: Array) {
val numberArray: IntArray = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
var reversedArray = numberArray.reversedArray()
println(Arrays.toString(reversedArray))
}
This will print the below output :
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Explanation :
In this example, we have used reversedArray() method to reverse the array numberArray. This method returns the reversed array. We are storing it in a different variable and then printing out the result.
Reverse an array in place :
fun main(args: Array) {
val numberArray: IntArray = intArrayOf(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
numberArray.reverse()
println(Arrays.toString(numberArray))
}
Output :
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
Explanation :
This example is different than the previous one. Here, we are reversing the array in place, i.e. the original array is reversed. If you don’t want to do anything with the original array, you can use this method to do the modification on the original array directly.
- Kotlin example program to find out the largest element in an array
- Kotlin program to find out the factors of a number
- Data class in Kotlin : Explanation with example
- What is primary constructor and secondary constructor in Kotlin
- Kotlin program to check if an alphabet is vowel or not
- Kotlin development tutorial – Array in Kotlin