how to reverse array in kotlin

Reversing an Array in Kotlin

To reverse an array in Kotlin, you can use the reversedArray() function. Here are the steps to reverse an array:

  1. Declare an array with the elements you want to reverse.
  2. Use the reversedArray() function on the array to reverse its order.
  3. Assign the reversed array to a new variable or overwrite the original array with the reversed array.

Here's an example of how to reverse an array in Kotlin:

val array = arrayOf(1, 2, 3, 4, 5)
val reversedArray = array.reversedArray()

// Alternatively, you can overwrite the original array with the reversed array:
// array.reverse()

println("Original array: ${array.contentToString()}")
println("Reversed array: ${reversedArray.contentToString()}")

Output:

Original array: [1, 2, 3, 4, 5]
Reversed array: [5, 4, 3, 2, 1]

In the example above, we first declare an array array with the elements [1, 2, 3, 4, 5]. We then use the reversedArray() function on array to obtain a new array reversedArray with the elements [5, 4, 3, 2, 1]. Finally, we print both the original and reversed arrays using the contentToString() function.

Note that the reversedArray() function returns a new array with the elements in reverse order, while the reverse() function modifies the original array in place.