How to reverse array in java – Java Program to Reverse Array Elements

How to reverse array in java: Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Java Program to Reverse Array Elements

  • Java program to reverse array elements and print it on screen using for loop.

In this java program, given an integer array of length N we have to print array elements in reverse sequence. In reversed array, first element of original array become the last element, second element becomes second last element and so on.

For Example,
Input Array : [2 5 3 4 6 7 8 1 0 3]
Reversed Array : [3 0 1 8 7 6 4 3 5 2]
Algorithm to print array in reverse order
Let inputArray is an integer array of length N.

  • Declare another array of size N, let it be “reverseArray”.
  • Using a for loop, copy elements from inputArray to reverseArray in reverse order. For example, copy last element of inputArray to first position of reverseArray and so on.
  • Now, using a for loop, traverse reverseArray from index 0 to N-1 and print elements on screen.

Java program to print array elements in reverse order

Java program to print array elements in reverse order

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to reverse an array
 */
public class ReverseArray {
    public static void main(String args[]) {
        int count, i;
        int input[] = new int[100];
        int output[] = new int[100];
 
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Number of Elements in Array");
        count = scanner.nextInt();
 
        /*
         * Take array input from user
         */
        System.out.println("Enter " + count + " Numbers");
        for (i = 0; i < count; i++) {
            input[i] = scanner.nextInt();
        }
 
        /*
         * Copy numbers from input to output Array in reverse order
         */
        for (i = 0; i < count; i++) {
            output[i] = input[count - i - 1];
        }
 
        /*
         * Print Reversed array
         */
        System.out.println("Reversed Array");
        for (i = 0; i < count; i++) {
            System.out.print(output[i] + " ");
        }
    }
}

Output

Enter Number of Elements in Array
8
Enter 8 Numbers
1 2 3 4 5 6 7 8
Reversed Array
8 7 6 5 4 3 2 1