Mz23
Mz23

Reputation: 21

Reverse array with for loop in Java

I was wondering if you can help me around this code. It should reverse content of array but I get this. Does anyone know how to fix this?

import java.util.Arrays;

public class Arrays7 {

    public static void main(String[] args) {
        // Write a Java program to reverse an array of integer values.
        
        int arr[] = { 1, 2, 3, 4, 5};
        int petlja[] = { 0, 0, 0, 0, 0 };       
        
         /* arr[0] = petlja[4];
        arr[1] = petlja[3];
        arr[2] = petlja[2];
        arr[3] = petlja[1];
        arr[4] = petlja[0];
        */
        
        for ( int i=4; i>0; i--) {
            for ( int j=0; j<4; j++) {
                petlja[j] = arr[i];
            }
        }
        
        System.out.println(Arrays.toString(petlja));

Upvotes: 2

Views: 1740

Answers (2)

Spectric
Spectric

Reputation: 31987

You can do it like so:

    for(int i = 0; i < array.length; i++) {
        petlja[i] = arr[array.length-i-1];
    }

Sample I/O

Input

1, 2, 3, 4, 5

Output

5, 4, 3, 2, 1

Upvotes: 0

Mureinik
Mureinik

Reputation: 311188

You don't need a nested loop - you need only one loop to go over the array and assign each element to the corresponding "reversed" array:

for (int i = arr.length - 1; i >= 0; i--) {
    petlja[petlja.length - i] = arr[i];
}

Upvotes: 1

Related Questions