Java Program to reverse the Array

17
views
Reverse the Array
(Last Updated On: February 18, 2019)

In this program, you’ll learn how to reverse the Array in java.

To properly understand this Program to reverse the Array, you should have the knowledge of following Java programming topics:

  • Java Array
  • Java loops
  • Basic operator

Program to reverse an Array

import java.util.Scanner;
public class Example
{
   public static void main(String args[])
   {
	int counter, i=0, j=0, temp;
	int number[] = new int[100];
	Scanner scanner = new Scanner(System.in);
	System.out.print("How many elements you want to enter: ");
	counter = scanner.nextInt();

	for(i=0; i<counter; i++)
	{
	    System.out.print("Enter Array Element"+(i+1)+": ");
	    number[i] = scanner.nextInt();
	}

	j = i - 1;     
	i = 0;         
	scanner.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

Ask your questions about how to reverse an Array in Java and clarify your/others doubts by commenting. Documentation.

Related Java Programs

Please write to us at [email protected] to report any issue with the above content or for feedback.