Scala program to swap adjacent elements in the array

Here, we are going to learn how to swap adjacent elements in the array in Scala programming language?
Submitted by Nidhi, on May 26, 2021 [Last updated : March 10, 2023]

Scala – Swap Adjacent Elements of an Array

Here, we will create an array of integer elements then we will swap adjacent elements in the array and print the updated array on the console screen.

Scala code to swap adjacent elements in the array

The source code to swap adjacent elements in the array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to swap adjacent elements
// in the array

object Sample {
  def main(args: Array[String]) {
    var IntArray = Array(10, 20, 30, 40, 50, 60)
    var i: Int = 0
    var t: Int = 0

    //swap adjacent elements
    while (i < 6) {
      t = IntArray(i);
      IntArray(i) = IntArray(i + 1);
      IntArray(i + 1) = t;

      i = i + 2;
    }

    println("Resulted array: ");
    i = 0;
    while (i < 6) {
      printf("%d ", IntArray(i));
      i = i + 1;
    }
    println()
  }
}

Output

Resulted array: 
20 10 40 30 60 50

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 an array IntArray. Each array contains 6 integer items. Then we swapped the adjacent elements of the array and then we printed the updated array on the console screen.

Scala Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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