341,346 views
38 votes
38 votes
Write a method reverse that takes an array as an argument and returns a new array with the elements in reversed order. Do not modify the array.

User Federico Capello
by
2.8k points

2 Answers

16 votes
16 votes

Final answer:

A method to reverse an array can be implemented in programming languages, and the example provided illustrates how to do this in Java by creating a new array to hold reversed elements without modifying the original array.

Step-by-step explanation:

To write a method that reverses the order of elements in an array without modifying the original array, you can use a programming language such as Java or Python. Below is an example of how this can be done in Java:

public static int[] reverse(int[] original) {
int[] reversed = new int[original.length];
for (int i = 0; i < original.length; i++) {
reversed[i] = original[original.length - 1 - i];
}
return reversed;
}

In this example, the method 'reverse' takes an array of integers 'original' as a parameter and creates a new array 'reversed' with the same length. Then, with the help of a for loop, it fills the 'reversed' array with elements from the 'original' array in reversed order by accessing the elements from the end to the beginning. Finally, it returns the 'reversed' array, which contains the elements in reverse order.

User Vishal Rao
by
3.2k points
13 votes
13 votes

Answer:

public class ArrayUtils

{

//function to reverse the elements in given array

public static void reverse(String words[])

{

//find the length of the array

int n = words.length;

//iterate over the array up to the half

for(int i = 0;i < (int)(n/2);i++)

{

//swap the first element with last element and second element with second last element and so on.

String temp;

temp = words[i];

words[i] = words[n - i -1];

words[n - i - 1] = temp;

}

}

public static void main(String args[])

{

//create and array

String words[] = {"Apple", "Grapes", "Oranges", "Mangoes"};

//print the contents of the array

for(int i = 0;i < words.length;i++)

{

System.out.println(words[i]);

}

//call the function to reverse th array

reverse(words);

//print the contents after reversing

System.out.println("After reversing............");

for(int i = 0;i < words.length;i++)

{

System.out.println(words[i]);

}

}

Step-by-step explanation:

User Quake
by
3.1k points