131k views
3 votes
6.9.1: Modify an array parameter. Write a function SwapArrayEnds() that swaps the first and last elements of the function's array parameter. Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}.

User Holgerwa
by
4.6k points

2 Answers

3 votes

Final answer:

To swap the first and last elements of an array in a function, create a function named SwapArrayEnds() that takes an array as a parameter. Within the function, use a temporary variable to store the first element of the array, assign the last element to the first position, and assign the temporary variable's value to the last position.

Step-by-step explanation:

To swap the first and last elements of an array in a function, you can create a function named SwapArrayEnds() that takes an array as a parameter. Within the function, you can use a temporary variable to store the first element of the array, assign the last element to the first position, and assign the temporary variable's value to the last position. Here is an example:

function SwapArrayEnds(arr) {
let temp = arr[0];
arr[0] = arr[arr.length - 1];
arr[arr.length - 1] = temp;
}
let sortArray = [10, 20, 30, 40];
SwapArrayEnds(sortArray);
console.log(sortArray);

In this example, the function SwapArrayEnds() swaps the first and last elements of the sortArray. After calling the function, the sortArray will be modified to [40, 20, 30, 10].

User Ben Trewern
by
4.4k points
4 votes

Answer:

public static void SwapArrayEnds(int[] arr) {

int temp = arr[0];

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

arr[arr.length-1] = temp;

}

Step-by-step explanation:

- Create a function called SwapArrayEnds that takes one parameter, an integer array

- Inside the function, declare a temporary variable and set it to the first element of the array

- Assign the value of the last element of the array to the first element, the first element in the array is swapped

- Assign the value of the temporary variable to the last element, the last element in the array is swapped

User Hanif Azhari
by
4.9k points