Learn how to reverse an array in Java using a for loop. here we are traverse an array from the last index to the first and display elements in reverse order.
Code Explanation (Step-by-Step)
- Creates a Scanner object to read user input from the keyboard.
- Creates an integer array with a maximum size of 20 elements.
- Uses the sc.nextInt() method to read the number of elements entered by the user and stores it in the variable n.
- Starts a for loop to read and store the array elements.
- Reads each element entered by the user and stores it in the array at index i.
- Prints a heading before displaying the array in reverse order.
- Starts a loop from the last index of the array and moves backward to the first index.
- Prints each array element in reverse order.
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter the number of elements:- ");
int n = sc.nextInt();
System.out.println("Enter the elements:- ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array in reverse order :- ");
for (int j = (n - 1); j >= 0; j--) {
System.out.print(arr[j] + " ");
}
sc.close();
}
}
Output :-
Enter the number of elements:-
4
Enter the elements:-
11
12
13
14
Array in reverse order :- 14 13 12 11
Java Program to Reverse an Array Without Using Another Array
import java.util.Scanner;
public class ReverseArrayInPlace {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter the number of elements:");
int n = sc.nextInt();
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int start = 0;
int end = n - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
System.out.println("Array after reversing:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
sc.close();
}
}
Here are some related Java 8 programs that will help you understand Stream API concepts better: