Write a static method which takes an array of ints as its argument, and reverses
ID: 3565746 • Letter: W
Question
Write a static method which takes an array of ints as its argument, and reverses the order of the elements in the array. That is, the first and last elements are switched, the second and second last elements are switched, etc. For example, this method should change the array [1, 2, 3, 4] to the array [4, 3, 2, 1].
Write a driver file to test your method. It should call your method with at least three different inputs.
Hint: When an array is passed into a method as a parameter, what is passed in is the reference to the location of that array in memory, not the array itself.
Explanation / Answer
public class ArrayReverseOrder {
public static void main(String[] args) {
int[] argumentSet1 = new int[] { 1, 2, 3,4 };
int[] argumentSet2 = new int[] { 5, 6, 7 };
int[] argumentSet3 = new int[] { 9, 10, 11 };
argumentSet1=reverse(argumentSet1);
argumentSet2=reverse(argumentSet2);
argumentSet3=reverse(argumentSet3);
System.out.println("Array1 after reversal");
print(argumentSet1);
System.out.println("Array2 after reversal");
print(argumentSet2);
System.out.println("Array3 after reversal");
print(argumentSet3);
}
// Reverse the Array
public static int[] reverse(int[] intArray) {
int length=intArray.length;
int temp=0;
for (int index=0;index<(intArray.length)/2;index++) {
temp=intArray[index];
intArray[index]=intArray[length-1-index];
intArray[length-1-index]=temp;
}
return intArray;
}
// print the Array
public static void print(int[] intArray) {
for (int temp : intArray) {
System.out.print(temp+" ");
}
System.out.println();
}
}
************************Sample Output ***************************************
Compiling the source code....
$javac ArrayReverseOrder.java 2>&1
Executing the program....
$java -Xmx128M -Xms16M ArrayReverseOrder
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.