Here is a 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.
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(); System.out.println("Enter " + count + " Numbers"); for (i = 0; i < count; i++) { input[i] = scanner.nextInt(); } for (i = 0; i < count; i++) { output[i] = input[count - i - 1]; } 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