217k views
3 votes
In Java, write a method swapArrayEnds() that swaps the first and last elements of its array parameter. Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}.

import java.util.Scanner;

public class ModifyArray {

/* Your solution goes here */

public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
int numElem = 4;
int[] sortArray = new int[numElem];
int i;
int userNum;

for (i = 0; i < sortArray.length; ++i) {
sortArray[i] = scnr.nextInt();
}

swapArrayEnds(sortArray);

for (i = 0; i < sortArray.length; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
}
}

User Uros K
by
7.2k points

1 Answer

2 votes

Answer:

Step-by-step explanation:

To write the swapArrayEnds() method that swaps the first and last elements of an array in Java, you can do the following:

Create a new method with the following signature:

Copy code

public static void swapArrayEnds(int[] arr) {

// Your code goes here

}

Inside the method, create a temporary variable to store the value of the first element of the array.

Assign the value of the last element of the array to the first element.

Assign the value stored in the temporary variable to the last element of the array.

Your method should now look like this:

Copy code

public static void swapArrayEnds(int[] arr) {

int temp = arr[0];

arr[0] = arr[arr.length - 1];

arr[arr.length - 1] = temp;

}

This method will swap the first and last elements of the array. You can then call this method from your main method, passing in the array as an argument. The array will be modified in place, so you don't need to return anything from the method.

I hope this helps! Let me know if you have any questions.

User Rokas Rudzianskas
by
7.9k points