In this java program tutorial, we will write a java program to reverse an array. Before that, you may go through the following topic in java.
Explanation: In this java program we will take user input for the size of an array and array elements. The elements are reversed using for loop and while loop.
We will write two programs:
- Using for loop
- Using while loop
Java program to reverse an array without using another array
Source Code: reverse the array using for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.util.Scanner; public class Main { public static void main(String args[]) { int size, i; int arr[] = new int[50]; Scanner scan = new Scanner(System.in); System.out.print("Enter the size of a first array: "); size = scan.nextInt(); System.out.println("Enter " + size + " elements in first Array:"); for (i = 0; i < size; i++) arr[i] = scan.nextInt(); System.out.println("Original array: "); for (i = 0; i < size; i++) { System.out.print(arr[i] + " "); } System.out.println("\nArray in reverse order: "); for (i = size - 1; i >= 0; i--) { System.out.print(arr[i] + " "); } } } |
Output:
Enter the size of a first array: 5
Enter 5 elements in first Array:
10
20
30
40
50
Original array:
10 20 30 40 50
Array in reverse order:
50 40 30 20 10
Reverse the Array using while loop
In this program, we will create a separate user-defined function to reverse the array, and then we will print the reversed array.
Source Code: reverse an array using a while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.util.Scanner; public class Main { public static void main(String args[]) { int size, i; int arr[] = new int[50]; Scanner scan = new Scanner(System.in); System.out.print("Enter the size of a first array: "); size = scan.nextInt(); System.out.println("Enter " + size + " elements in first Array:"); for (i = 0; i < size; i++) arr[i] = scan.nextInt(); System.out.print("Original array: "); for (i = 0; i < size; i++) System.out.print(arr[i] + " "); //calling a function reverseFunc(arr, 0, size - 1); System.out.print("\nReversed array: "); for (i = 0; i < size; i++) System.out.print(arr[i] + " "); } static void reverseFunc(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } } |
Output:
Enter the size of a first array: 5
Enter 5 elements in first Array:
1
2
3
4
5
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1