
Java Program To Reverse The Array
In this Java Program, we reverse the array. In this program if a user enters numbers 1, 2, 3, 4, 5 then the program will reverse the array and the elements will be 5, 4, 3, 2, 1.
Array is a data structure consisting of collections of elements each identified by atleast one array index or key.
E.g. If you want to store 5 numbers in an array,
datatype arrayname [arraysize];
int a[5];
Step 1 : Import java.util.Scanner Class
Step 2 : Create and initialize variable i and j to 0, counter and temp.
Step 3 : Create an array named number and store value 100 in it.
Step 4 : Create the object of the Scanner class
Step 5 : Ask the user to the enter the number of elements he want to enter.
Step 6 : Store the user entered numbers in the variable counter
Step 7 : Apply for loop where i is equal o 0, i should be less than counter and increment i.
This loop stores all the elements that we enter in an array number. First element is at number[0], second at number[1] and so on.
Step 8 : Print the enter array element by adding 1 int the i.
Step 9 : Store the user entered number in the array of number[i]
Step 10 : Decrement i by 1 and store it in j. Here we are writing the logic to swap first element with last element, second last element with the second element and so on. On the first iteration of the while loop i is the index of first element and j is the index of last. On the second iteration i is the index of the second and j is the index of the second last.
Step 11 : Initialize i to 0
Step 12 : Close the Scanner class to avoid any memory leak.
Step 13 : Apply while loop where i should be less than j
Step 14 : Store array number[i] in the temp variable
Step 15 : Store array of number[i] in array of number[j]
Step 16 : Store array of number [j] in variable temp.
Step 17 : Increment i & decrement j
Step 18 : Print reversed array
Step 19 : Apply for loop where i should be equal to 0, i should be less than counter and increment i
Step 20 : Print the array of number [i]
Program :
import java.util.Scanner;
public class ReverseArray
{
public static void main(String args[])
{
int counter, i = 0, j = 0, temp;
int number[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.print("How many elements you want to enter:");
counter = sc.nextInt();
for(i = 0; i < counter; i++)
{
System.out.print("Enter Array Element"+(i + 1)+": ");
number[i] = sc.nextInt();
}
j = i - 1;
i = 0;
sc.close();
while(i < j)
{
temp = number[i];
number[i] = number[j];
number[j] = temp;
i++;
j--;
}
System.out.print("Reversed array:");
for(i = 0; i < counter; i++)
{
System.out.print(number[i]+" ");
}
}
}
Output:
How many elements you want to enter:5
Enter Array Element1: 11
Enter Array Element2: 22
Enter Array Element3: 33
Enter Array Element4: 44
Enter Array Element5: 55
Reversed array:55 44 33 22 11
For execution of the same do visit my You Tube Channel :