Skip to main content

How to reverse an array in Kotlin

How to reverse an array in Kotlin.

Here's a step-by-step tutorial on how to reverse an array in Kotlin:

Step 1: Create an array

To begin with, you need to create an array that you want to reverse. You can create an array using the arrayOf() function and pass the elements as arguments. For example, let's create an array of integers:

val numbers = arrayOf(1, 2, 3, 4, 5)

Step 2: Initialize variables

Next, you need to initialize two variables: start and end. The start variable will point to the first element of the array, while the end variable will point to the last element of the array. In Kotlin, you can get the index of the first and last elements using the startIndex and endIndex properties of the array.

var start = 0
var end = numbers.lastIndex

Step 3: Reverse the array

Now, you can start reversing the array by swapping the elements at the start and end indices. You can do this using a while loop that continues until the start index is less than the end index. Inside the loop, swap the elements using a temporary variable. After each swap, increment the start index and decrement the end index.

while (start < end) {
val temp = numbers[start]
numbers[start] = numbers[end]
numbers[end] = temp
start++
end--
}

Step 4: Print the reversed array

Finally, you can print the reversed array to verify the result. You can use the joinToString() function to convert the array elements into a string with a specific separator.

println(numbers.joinToString())

Here's the complete code:

val numbers = arrayOf(1, 2, 3, 4, 5)
var start = 0
var end = numbers.lastIndex

while (start < end) {
val temp = numbers[start]
numbers[start] = numbers[end]
numbers[end] = temp
start++
end--
}

println(numbers.joinToString())

When you run this code, it will output the reversed array:

5, 4, 3, 2, 1

That's it! You have successfully reversed an array in Kotlin.