Reverse Array Elements in Java
public class ReverseArray {
public static void main(String[] args) {
int[] intArr = new int[] { 1, 2, 3, 4, 5, 6, 7 };
System.out.println("Array elements before reverse");
displayArrayElements(intArr);
reverseArrayElements(intArr);
System.out.println("reversed array elements");
displayArrayElements(intArr);
}
public static void displayArrayElements(int[] arr) {
for (int temp : arr) {
System.out.println(temp);
}
System.out.println("..............................");
}
public static void reverseArrayElements(int[] arr) {
int temp = 0;
for (int start = 0, end = arr.length - 1; start < end; start++, end--) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
}
output
Array elements before reverse
1
2
3
4
5
6
7
..............................
reversed array elements
7
6
5
4
3
2
1
..............................
1
2
3
4
5
6
7
..............................
reversed array elements
7
6
5
4
3
2
1
..............................
No comments:
Post a Comment