Scala program to reverse an integer array

Here, we are going to learn how to reverse an integer array in Scala programming language?
Submitted by Nidhi, on May 08, 2021 [Last updated : March 10, 2023]

Scala – Reverse an Array

Here, we will create an integer array and then we will copy the elements of the array in reverse order into another array.

Scala code to reverse an integer array

The source code to reverse an integer array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to reverse an integer array

object Sample {  
    def main(args: Array[String]) {  
        var IntArray = Array(11,12,13,14,15)
        var RevArray = new Array[Int](5)
        
        var count1:Int=0
        var count2:Int=0
        
        
        //Reverse an array
        count1=0
        count2=4
        while(count1<5)
        {
            RevArray(count1)=IntArray(count2)
            
            count1=count1+1
            count2=count2-1
        }
        
        println("Array:")
        count1=0
        while(count1<5)
        {
            printf("%d ",IntArray(count1))
            count1=count1+1
        }
        println()
        
        println("Reversed Array:")
        count1=0
        while(count1<5)
        {
            printf("%d ",RevArray(count1))
            count1=count1+1
        }
        println()
    }
} 

Output

Array:
11 12 13 14 15 
Reversed Array:
15 14 13 12 11 

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created two integer arrays IntArray, RevArray.  The IntArray contains 5 integer elements. Then we copied the elements of IntArray into RevArray in revered order. After that, we printed the elements of both arrays on the console screen.

Scala Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.