Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Reverse array java

import java.util.Arrays; 

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        reverse(numbers);
        /*
            output is:
                Array = [1, 2, 3, 4, 5]
                Reversed array = [5, 4, 3, 2, 1]
        */
    }
    
    public static void reverse(int[] array) {
        System.out.println("Array = " + Arrays.toString(array));
        int maxIndex = array.length - 1;
        int halfLength = array.length / 2;
        for (int i = 0; i < halfLength; i++) {
            int temp = array[i];
            array[i] = array[maxIndex - i];
            array[maxIndex - i] = temp;
        }
        System.out.println("Reversed array = " + Arrays.toString(array));
    }
}
 
PREVIOUS NEXT
Tagged: #Reverse #array #java
ADD COMMENT
Topic
Name
4+2 =