Scala program to reverse an array

1. Introduction

Reversing an array is a fundamental operation in computer science and can be used in various algorithms and problem-solving scenarios. Scala, with its fusion of functional and object-oriented programming paradigms, provides multiple ways to reverse an array. Here, we'll look at a straightforward method to achieve this.

2. Program Steps

1. Initialize the Scala environment.

2. Create a sample array.

3. Utilize the reverse method to reverse the elements of the array.

4. Display the original and reversed array.

5. Execute the program.

3. Code Program

object ArrayReverseApp {
  def main(args: Array[String]): Unit = {
    // Sample array
    val numbers = Array(1, 2, 3, 4, 5)

    // Reverse the array
    val reversedNumbers = reverseArray(numbers)

    println(s"Original Array: ${numbers.mkString("[", ", ", "]")}")
    println(s"Reversed Array: ${reversedNumbers.mkString("[", ", ", "]")}")
  }

  def reverseArray(arr: Array[Int]): Array[Int] = {
    arr.reverse
  }
}

Output:

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

Explanation:

1. We define an ArrayReverseApp object as our main program container.

2. Inside the main function, we initialize a sample array named numbers.

3. The reverseArray function is defined to take an array as an input and return its reversed version. For this, it uses the built-in reverse method provided by Scala's Array class.

4. Both the original and reversed arrays are printed to the console using the mkString method, which is a convenient way to convert arrays to strings with custom delimiters.


Comments