Reversing an array is a common task. One approach copies to a second array in reverse, then copies the second array back to the first. However, to save space, reversing an array without using a second array is sometimes preferable. Write a code in java that reads in an integer representing the length of the array. Then read in and reverse the given array, without using a second array. If the original array's values are 2 5 9 7, the array after reversing is 7 9 5 2.
Hints:
Use this approach: Swap the first and last elements, then swap the second and second-to-last elements, etc.
Stop when you reach the middle; else, you'll reverse the vector twice, ending with the original order.
Think about the case when the number of elements is even, and when odd. Make sure your code handles both cases.
Please find below code and don't forget to give a Like.
Please refer below screenshot for code and output
Code:
public class Main
{
public static void main(String[] args) {
int[]
array={10,20,30,40,50,60};
int temp;
int rev=array.length-1;//from last
element we decrement by 1
int
middle_element=array.length/2;
//printing the original
elements
System.out.println("The original
elements in array are:");
for(int
i=0;i<array.length;i++){
System.out.println(array[i]);
}
for(int
i=0;i<=middle_element;i++){
temp=array[i];//storing 1st element
in temporary varible
array[i]=array[rev];//assigning
last element into first
//swaping last element with
temporary value which is saved
array[rev]=temp;
rev-=1//starting from last element
will be decrement by 1
}
//printing thr reverse array
System.out.println("The reverse
elements are:");
for(int
i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.