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.
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.
Output:
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