on Leave a Comment

Java Program to Reverse an Array

This java program reverse an array. First, you have to enter the size of array, then enter array elements using keyboard. Then sorts array using for loop. Finally, display reversed array. 

The for loop which is actually reversing array, using three variables ij and temp. Variable j is containing index of last element and i contains index of first element and swapping is performed between arr[i] and arr[j] using temp variable. After swapping, j decrements and i increments, and for loop again executes until condition (i<j) hold true.

Java Source Code to Reverse an Array

import java.util.Scanner;

public class ReverseArray
{
   public static void main(String args[])
   {
       int size;
       Scanner scan = new Scanner(System.in);
    
       System.out.print("Enter Size of Array  : ");
       size = scan.nextInt();

       int arr[] = new int[size];
       int i, j, temp;

       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
    
       //Reversing Array Using for Loop
       for(j = size-1, i = 0; i<j; j--, i++)
       {
           temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
       }
    
       System.out.print("Reversed Array is : ");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i]+ "  ");
       }       
   }
}

Output:

Enter Size of Array  : 5
Enter Array Elements : 1 2 3 4 5
Reversed Array is : 5  4  3  2  1

0 comments:

Post a Comment