How do i reverse an array in kotlin

Published October 07, 2021


In this kotlin example we will learn how to reverse an array. To reverse an array we have two methods

  • reverse()
  • reversedArray()

By using abpve two method we will write kotlin program to reverse the int array.

 

Let's get started

Step 1: Create an Array with fixed size.

Step 2: Write for loop to ask user to enter array elements using scanner class

Step 3: Take user inputs and add inside created Int array

 

Using reversedArray:

Step 4: Now apply reversedArray method on given array. It will reverse the given array and returns new array.

Step 5: Assign return array to new var and print the new array.

import java.util.*

fun main() {
    var k:Int;
    var inputArray: IntArray =IntArray(5);
    val integer = Scanner(System.`in`)
    for( k in 0..4)
    {

        print("Enter an integer at position $k : ")
        var enteredinteger:Int = integer.nextInt()
        inputArray[k]=enteredinteger
    }
    println("Given array : ${Arrays.toString(inputArray)}")

    var reversedArray = inputArray.reversedArray()

    println("Reversed array : ${Arrays.toString(reversedArray)}")


}

 

Output:

Enter an integer at position 0 : 12
Enter an integer at position 1 : 1
Enter an integer at position 2 : 23
Enter an integer at position 3 : 14
Enter an integer at position 4 : 123
Given array : [12, 1, 23, 14, 123]
Reversed array : [123, 14, 23, 1, 12]

 

 

using reverse(): This reverse method instead of create new array it will modifies original array.

Step 4: Now apply reversed() method on given array.

Step 5: Now print the array.

 

import java.util.*

fun main() {
    var k:Int;
    var inputArray: IntArray =IntArray(5);
    val integer = Scanner(System.`in`)
    for( k in 0..4)
    {

        print("Enter an integer at position $k : ")
        var enteredinteger:Int = integer.nextInt()
        inputArray[k]=enteredinteger
    }
    println("Given array : ${Arrays.toString(inputArray)}")

    inputArray.reverse()

    println("Reversed array : ${Arrays.toString(inputArray)}")


}

 

Output:

Enter an integer at position 0 : 12
Enter an integer at position 1 : 34
Enter an integer at position 2 : 2
Enter an integer at position 3 : 1
Enter an integer at position 4 : 345
Given array : [12, 34, 2, 1, 345]
Reversed array : [345, 1, 2, 34, 12]

 

 

Conclusion: In this example we covered how to reverse an array using revers() and reversedArray() methods.


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

8 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions