-3

I'm trying to reverse an array, but I don't know how to get the correct output (4,3,2). My questions are; how do I print the output (using System.out.println())? Nothing I've tried works. My second question is; is the rest of my code correct?

public static void main(String[] args) {
int arr[] = {2,3,4};
int i = 0;
int j = arr.length - 1;


while( i < j ) {

    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;


    i++;
    j--;
}
}
javac
  • 1
  • 2
    First try your self in google.You will get so many results for this – PSR Dec 05 '16 at 13:07
  • 2
    **1.** `System.out.println(Arrays.toString(arr))` **2.** Please check it by yourself, and if you have problems let us know. – Maroun Dec 05 '16 at 13:07
  • Write 2,3 and 4 on scraps of paper, arrange them in a row, then walk through your while loop manually to see if it works. If not, come up with something else that does. – slim Dec 05 '16 at 13:13
  • @Gatusko no it isn't. – slim Dec 05 '16 at 13:15

1 Answers1

1

Just printing arrays in reverse order:

int arr[] = {2,3,4};
int i=arr.length;
while(0<i--)
  System.out.println(arr[i]);

Reversed array by copying:

int arr[]={2,3,4};
int i=arr.length,j=0;
int rev[]=new int[i];//to copy array

while(0<i)
  rev[j++]=arr[--i];//copy array in reverse order

for(int e:rev)//printing reversed array
  System.out.println(e);