You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.6 KiB

import java.util.Arrays;
public class ArrayManipulation {
public static int[] reverseArray(int[] arr) {
for (int i = 0; i < arr.length/2; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
return arr;
}
public static int[] removeFirst(int[] arr) {
return Arrays.copyOfRange(arr, 1, arr.length); // Copys the array "arr" from place 1 for the whole length of the array
}
public static int[] removeLast(int[] arr){
int arr2[];
if(arr.length<=1) return arr2 = new int[0]; //if array only has 1 elements, give empty array
arr2 = new int[arr.length-1]; //else make new array with length one less
for(int i=0; i<arr.length-1; i++){
arr2[i]=arr[i]; //copy all but the last elements of original array
}
return arr2; //return new array
}
public static int[] squareEach(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * arr[i];
}
return arr;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
System.out.println(Arrays.toString(removeFirst(arr))); // prints out the array on the Terminal which used the removefirst method
System.out.println(Arrays.toString(removeLast(arr)));
System.out.println(Arrays.toString(squareEach(arr)));
System.out.println(Arrays.toString(reverseArray(arr))); // prints out the array reversed on the Terminal which used the reversearray method
}
}