3

I am a newbie in Java. I wrote this program to reverse an array:

public class Reverse {

    public static void main(String[] args) {

        int num[] = {55, 2, 37, 9, 8};

        System.out.println("Original array is: ");
        for (int i : num)
            System.out.print(i + " ");

        for (int i = 1 ; i  != 5; i++) {
            num[i - 1] = num[num.length - i];
        }

        System.out.println("\nReversed array is: ");
        for (int i : num)
            System.out.print(i + " ");

        System.out.println(" ");

    }
}

But I am getting the below result. Do you guys know what I am doing wrong?

Original array is: 55 2 37 9 8 Reversed array is: 8 9 37 9 8

1
  • In summary there are lots of ways to accomplish this. But doing it the way you did, you may want to restructure your for loop to for(int i = 1; i < 5; i++) Commented Aug 27, 2013 at 4:57

7 Answers 7

2

You can swap the front and back elements of the array.

This way saves space.

int[] array = {1, 2, 3, 4, 5};

for (int i = 0; i < array.length/2; i++)
{
   int tmp = array[i];
   array[i] = array[array.length - i - 1];
   array[array.length - i - 1] = tmp;
}

// array is now reversed in place

If you don't want to change the contents of the original array, you can copy it into a new array of equal length:

int[] array = {1, 2, 3, 4, 5};
int[] reversedArray = new int[array.length];

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

// print out contents of reversedArray to see that it works
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I don't understand -> array.length/2. why is the array length being divided by 2?
Because you only need to go through half of the array to swap them in place. :)
You don't need to iterate over the entire array since you are swapping two elements during each iteration. Hence, array.length / 2.
@user2056083 Best way to thank is to accept the answer if it worked for you , its pretty simple :)
2

You're copying the values over the original array in your second for loop, The SIMPLEST (read: not necessarily best or most efficient) solution is to create a new array and copy the values there.

int[] backwardsArray = new int[5];

for (int i = 0; i < 5; i++) {
    backwardsArray[i] = num[4-i];
}

This will sequentially making the following value assignments:

backwardsArray[0] = num[4];
backwardsArray[1] = num[3];
backwardsArray[2] = num[2];
backwardsArray[3] = num[1];
backwardsArray[4] = num[0];

In general, you should always use a debugger to step into your code to understand why it is not behaving as you expect.

2 Comments

thank you for your prompt response :)
@user2056083 No problem, if you have no further questions and are happy with this answer, you can click the check mark under my score to mark the answer as accepted. Or feel free to ask more questions, etc.
1

You could do the following: (does not require addtional libraries)

List aList = Arrays.asList(yourArray)
Collections.reverse(aList);
yourArray = aList.toArray()

Comments

0

Actually what was wrong in your program is num[i - 1] = num[num.length - i]; this statement.

What is does? simply it replace the num[0] with num[4] and num[0] is lost forever. that's why you are loosing value 55. and solution for this is to use second array to store the reverse value as suggested by Kon.

Comments

0
public static void main(String[] argc) {

    int num[] = {55, 2, 37, 9, 8};

    System.out.println("Original array is: ");
    for (int i : num)
        System.out.print(i + " ");

    for (int i = 0 ; i < num.length / 2; i++) {
        int temp = num[i];
        num[i] = num[num.length -1 - i];
        num[num.length - i - 1] = temp;
    }

    System.out.println("\nReversed array is: ");
    for (int i : num)
        System.out.print(i + " ");

    System.out.println(" ");
    }

Comments

0
ArrayUtils.reverse(num);

I would use the Appache Common library. It's both convenient and worry-free.

1 Comment

That's okay but I believe that for a beginner, external libraries should be left out for those basic projects. Those are definitely more optimized but basics are still basics.
0

`The problem is that you're overwriting your indexes and at end, you come to same values that you've been setting in the beginning. For your case, the programs works like this:

num[4] -> num[0] -- 8 overwrites 55, num = {8,2,37,9,8}
num[3] -> num[1] -- 9 overwrites 2, num = {8,9,37,9,8}
num[2] -> num[2] -- 37 gets set to same index, num = {8,9,37,9,8}
num[1] -> num[3] -- 9 gets set to overwrited value of 2 (now 9), num = {8,9,37,9,8}
num[0] -> num[4] -- 8 gets set to overwrited value of 55 (now 8), num = {8,9,37,9,8}

The most simple solution to understand is (using your code):

int reversedArray[] = new int[num.Length];
for (int i = 1 ; i  != 5; i++) {
     reversedArray[i - 1] = num[num.length - i];
}

And some tips on your code:

  • use {object type}[] array = ... instead of {object type} array[]. Although it works, if you're ever going to transfer to C#, this might give you problems. On the other hand, this is correct syntax for c/c++.
  • in for loop, instead of initializing i at 1, start it at 0 as the all arrays are zero-based (this means the first index has a number of 0). This way you can index array only with i, not having to additionally subtract it.
  • Also, for the condition, use i < array.Length. This will end 1 number before the number you've put in. For your example, it would loop from 0 to 4 and when it hits 5, it won't repeat the loop again. Again, your syntax works, but the other one is more logical to understand. Also, it might happen (in more complex program scenarios) that looping this way will not give you the result expected, causing you huge headaches because of very simple error.

A more correct solution (applying my tips to your code):

int[] reversedArray = new int[num.Length];
for (int i = 0 ; i < num.Length; i++) {
     reversedArray[i] = num[num.length - i];
}

I see that in the time I was writing this, some new questions were added, but I hope that mine helped you understand what was your error and why did it happen.

2 Comments

it most definitely helped! i was specifically trying to understand why my code did not work
I'd appreciate accepted question or at least a upvote :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.