In this tutorial, we will learn to write a program in java to reverse an array without using any other array. This array reversal is also known as in place array reversal program in java.
Program 1 : Array Reversal Program in Java without using temp array and variable
- In the below program we are not using any temp array to reverse the array.
- This program is something like reversing the original array.
- Here we are using the concept of swapping the number to reverse the array.
import java.util.*;
public class Main
{
public static void main(String[] args) {
int startIndex,lastIndex;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size];
for(int i=0; i<size; i++) {
System.out.print("Please give value for index "+ i +" : ");
arr[i] = sc.nextInt();
}
startIndex = 0;
lastIndex = size - 1;
while (startIndex < lastIndex)
{
arr[startIndex] = arr[startIndex] + arr[lastIndex];
arr[lastIndex] = arr[startIndex]- arr[lastIndex];
arr[startIndex] = arr[startIndex]- arr[lastIndex];
startIndex++;
lastIndex--;
}
System.out.println("Array After Reversing :");
for(int i=0; i<size; i++)
{
System.out.println(arr[i]);
}
}
}
Output