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.
-
Importing Required Class:
- The
java.util.Scanner
class is imported to handle user input.
- The
-
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 variablesize
.
-
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
.
- An integer array
-
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 reaches0
. - During each iteration, the current element is printed.
- The program uses a
-
Output:
- The elements are printed in reverse order, separated by spaces.
Key Features:
- Manual Reversal:
- Instead of using built-in methods like
Collections.reverse()
, this program implements the reversal logic manually using a simplefor
loop.
- Instead of using built-in methods like
- Efficiency:
- The loop iterates through the array once, making this approach efficient in terms of time complexity (
O(n)
).
- The loop iterates through the array once, making this approach efficient in terms of time complexity (
- No Additional Memory:
- The program does not require converting the array to a
List
or creating additional data structures, making it memory-efficient.
- The program does not require converting the array to a
- Flexibility:
- This method can be applied to any array, regardless of its type or size.
- Output Formatting:
- The reversed elements are printed on a single line, separated by spaces.
- 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