Task #10: Using Arrays and Methods
In this task, you are being asked to write methods that manipulate arrays in Java.
Write a method that returns the reverse of a given integer array.
You may use the following header for this method:
static int[] reverseArray(int[] array)
For example, suppose that the array has 10 values: 10 9 8 7 6 5 4 3 2 1
The method will return an array which would contain the values: 1 2 3 4 5 6 7 8 9 10
NOTE: Declare and initialize the array without taking the input from user.
4. Create a program called ArrayReverseLab1.java.
5. Create appropriate variables and assign values using a Scanner object.
6. Correctly display appropriate messages.
import java.util.Arrays;
public class ArrayReverseLab1 {
static int[] reverseArray(int[] array) {
int[] reversed = new int[array.length];
for (int i = 0; i < array.length; i++) {
reversed[array.length - 1 - i] = array[i];
}
return reversed;
}
public static void main(String[] args) {
int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
System.out.println(Arrays.toString(reverseArray(array)));
}
}
Comments
Leave a comment