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

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 

Recommended Posts
Java Program to Search an Element in an Array using Linear Search
Java Program to Find Sum of Elements of an Array
Java Program to Merge Two Sorted Arrays
Java Program to Find Average of all Array Elements
Java Program to Insert an Element in Array at Given Position
Java Program to Find Duplicate Elements in an Array
C++ Program to Find Smallest Element in Array
C++ Program to Find Largest Element of an Array
Java Program to Find Largest of Three Numbers
Java Program to Find LCM and GCD of Two Numbers
Java Program to Check a Number is Prime Number or Not
All Java Programs