2

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));
2
  • 5
    I think you're just guessing, which doesn't help you learn. Write down the steps to do this by hand. Then try to duplicate those steps on the computer. Hint: you only need one loop, not two nested loops. Commented Sep 25, 2020 at 19:39
  • If you still aren't able to figure out, Swap the first and the last element of the array and write down how the computer will execute it and according set the condition. Commented Sep 26, 2020 at 1:09

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.