Q:

Scala program to swap adjacent elements in the array

belongs to collection: Scala Array Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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 »

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to find the total occurrences of a g... >>
<< Scala program to add two matrices...