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.

44 lines
1.3 KiB

2 years ago
2 years ago
  1. import java.util.Arrays;
  2. public class ArrayManipulation {
  3. public static int[] reverseArray(int[] arr) {
  4. for (int i = 0; i < arr.length / 2; i++) {
  5. int tmp = arr[i];
  6. arr[i] = arr[arr.length - 1 - i];
  7. arr[arr.length - 1 - i] = tmp;
  8. }
  9. return arr;
  10. }
  11. public static int[] squareEach(int[] arr){
  12. int[] square = new int[arr.length];
  13. for (int i = 0; i < arr.length; i++) {
  14. square[i] = arr[i] * arr[i];
  15. }
  16. return square;
  17. }
  18. public static int[] removeFirst(int[] arr){
  19. int[] firstRemoved = new int[arr.length -1];
  20. for(int i = 0; i < firstRemoved.length; i = i + 1) {
  21. firstRemoved[i] = arr[i + 1];
  22. }
  23. return firstRemoved;
  24. }
  25. public static int[] removeLast(int[] arr) {
  26. int[] lastRemoved = new int [arr.length - 1];
  27. for (int i = 0; i < lastRemoved.length; i = i + 1) {
  28. lastRemoved[i] = arr[i];
  29. }
  30. return lastRemoved;
  31. }
  32. public static void main(String[] args) {
  33. int[] arr = { 1, 2, 3, 4, 5 };
  34. System.out.println(Arrays.toString(reverseArray(arr)));
  35. System.out.println(Arrays.toString(squareEach(arr)));
  36. System.out.println(Arrays.toString(removeLast(arr)));
  37. System.out.println(Arrays.toString(removeFirst(arr)));
  38. }
  39. }