Java program to reverse array using for loop

Program

import java.util.Scanner;
public class ReverseArrayUsingForLoop {
  public static void main(String[] args) {
    int i=0;
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    int inputArray[] = new int[size];
    System.out.println("Enter the elements of the array: ");
    for (i = 0; i < size; i++) {
      inputArray[i] = reader.nextInt();
    }
    System.out.println("Array in reverse order: ");
    for (i = inputArray.length-1; i >= 0; i--) {  
        System.out.print(inputArray[i] + " ");  
    }   
  }
}

This Java program demonstrates how to reverse the elements of an array manually using a for loop.

  1. Importing Required Class:

    • The java.util.Scanner class is imported to handle user input.
  2. Reading the Array Size:

    • The program prompts the user to enter the size of the array.
    • The input size is read using a Scanner object and stored in the variable size.
  3. Creating and Populating the Array:

    • An integer array inputArray is created with the specified size.
    • The user is prompted to enter the elements of the array, which are stored one by one in inputArray.
  4. Reversing the Array Using a for Loop:

    • The program uses a for loop to iterate through the array in reverse order.
    • The loop starts from the last index of the array (inputArray.length - 1) and decrements the index until it reaches 0.
    • During each iteration, the current element is printed.
  5. Output:

    • The elements are printed in reverse order, separated by spaces.

Key Features:

  1. Manual Reversal:
    • Instead of using built-in methods like Collections.reverse(), this program implements the reversal logic manually using a simple for loop.
  2. Efficiency:
    • The loop iterates through the array once, making this approach efficient in terms of time complexity (O(n)).
  3. No Additional Memory:
    • The program does not require converting the array to a List or creating additional data structures, making it memory-efficient.
  4. Flexibility:
    • This method can be applied to any array, regardless of its type or size.
  5. Output Formatting:
    • The reversed elements are printed on a single line, separated by spaces.
  6. User Input:
    • Ensure the user enters valid integers as input to avoid runtime errors.

Output

javac .\ReverseArrayUsingForLoop.java
java ReverseArrayUsingForLoop        
Enter the required size of the array: 
5
Enter the elements of the array: 
10
20
30
40
50
Array in reverse order: 
50 40 30 20 10