w3resource

Scala Programming: Reverse an array of integer values

Scala Programming Array Exercise-12 with Solution

Write a Scala program to reverse an array of integer values.

Sample Solution:

Scala Code:

object Scala_Array {   
  def test(nums: Array[Int]): Array[Int] = {
    var temp1 = 0
    var temp2 = 0
    var index_position = 0
    var index_last_pos = nums.length - 1   
    while (index_position < index_last_pos) {
    temp1 = nums(index_position)
    temp2 = nums(index_last_pos)
    nums(index_position) = temp2
    nums(index_last_pos) = temp1
    index_position += 1
    index_last_pos -= 1
     }
    nums
  }       
   def main(args: Array[String]): Unit = {
    var nums1 = Array(1789, 2035, 1899, 1456, 2013) 
    println("Orginal array:")
    for ( x <- nums1) {
       print(s"${x}, ")        
     }           
    var result1= test(nums1)
    println("\nReversed array:")
    for ( x <- result1) {
       print(s"${x}, ")        
     }     
    var nums2 = Array(1789, 2035, 1899, 1456)           
    println("\nOrginal array:")
    for ( x <- nums2) {
       print(s"${x}, ")        
     }       
    var result2= test(nums2)
    println("\nnReversed array:")
    for ( x <- result2) {
       print(s"${x}, ")   
    }
   }
}

Sample Output:

Orginal array:
1789, 2035, 1899, 1456, 2013, 
Reversed array:
2013, 1456, 1899, 2035, 1789, 
Orginal array:
1789, 2035, 1899, 1456, 
nReversed array:
1456, 1899, 2035, 1789, 

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to create a new array taking the middle element from three arrays of length 5.
Next: Write a Scala program to check two numbers, 4 or 7 present in a given array of integers.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/array/scala-array-exercise-12.php