Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method swapArrayEnds() that swaps the first and last elements of its arr

ID: 3597995 • Letter: W

Question

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}. The array's size may differ from 4.

import java.util.Scanner;

public class ModifyArray {

/* Display array values */
public void displayValues(int [] arrayVals) {
int i;

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

/* Your solution goes here */

public static void main (String [] args) {
int numElem = 4;
int[] sortedArray = new int[numElem];
ModifyArray numInverter = new ModifyArray();

// Add values to the array
sortedArray[0] = 10;
sortedArray[1] = 20;
sortedArray[2] = 30;
sortedArray[3] = 40;

numInverter.swapArrayEnds(sortedArray);
numInverter.displayValues(sortedArray);
}
}

Explanation / Answer

ModifyArray.java

import java.util.Scanner;
public class ModifyArray {
/* Display array values */
public void displayValues(int[] arrayVals) {
int i;
for (i = 0; i < arrayVals.length; ++i) {
System.out.print(arrayVals[i] + " ");
}
System.out.println("");
}

private void swapArrayEnds(int[] sortedArray) {
int firstElement = sortedArray[0];
int lastElement = sortedArray[sortedArray.length - 1];
int temp;
temp = firstElement;
firstElement = lastElement;
lastElement = temp;
sortedArray[0] = firstElement;
sortedArray[sortedArray.length - 1] = lastElement;

}

public static void main(String[] args) {
int numElem = 4;
int[] sortedArray = new int[numElem];
ModifyArray numInverter = new ModifyArray();
// Add values to the array
sortedArray[0] = 10;
sortedArray[1] = 20;
sortedArray[2] = 30;
sortedArray[3] = 40;
numInverter.swapArrayEnds(sortedArray);
numInverter.displayValues(sortedArray);
}

}

_________________

Output:

40 20 30 10

_____________Could you rate me well.Plz .Thank You

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote