In: Computer Science
4. Please name your driver program XXX_P04 where XXX are your initials. Given the array inputArray (doubles), write a method called swap which will swap any two contiguous (next to each other) elements. Swap will be passed two parameters, the index of the first element to be swapped and the array name. Write another method printArray that will print the array 5 elements to a line. PrintArray will be passed one parameter the array name. See the videos for help with this. The array elements are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Java Eclipse
Code Screenshot :
Executable Code:
public class XXX_P04
{
//Main Program
public static void main(String[] args)
{
//Declaring required
array
double[] inputArray =
{1,2,3,4,5,6,7,8,9,10};
printArray(inputArray);
//Calling the
method
swap(5, inputArray);
System.out.println();
printArray(inputArray);
}
//Method to swap
public static void swap(int k, double [] input)
{
//Swapping the
elements
double temp = input[k];
input[k] = input[k+1];
input[k+1] = temp;
}
//Method to print the result
public static void printArray(double[] input) {
for(int i = 0; i < input.length;
++i) {
System.out.print(input[i] + " ");
//Printing the result
if((i+1) % 5 ==
0) {
System.out.println();
}
}
}
}
Sample Output:
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)