How can I arrange an array from 500 down to 1 in an array? (Java)

F-H :

I'm trying to arrange and printout an array starting at 500 and stopping at 1, I have tried this with the following code, but this will printout starting from 1 and going up to 500:

int [] aftel = new int [501];
for (int teller3 = 500; teller3 > 0; teller3--){
       aftel[teller3] = teller3;
    }
System.out.println(Arrays.toString(aftel));

However using the following code, the array will printout the correct way, but I'm trying to arrange the array fully before printing out values:

int [] aftel = new int [501];
for (int teller2 = 1; teller2 <= 500; teller2++){
        optel500[teller2] = teller2;
        System.out.print(optel500[teller2]+" ");
    }
Federico klez Culloca :

In your first loop, you're using teller3 as both an index and a value. That means that index 500 will have the value 500, which is the opposite of what you want.

You're also making a bit of confusion with the array size.

The correct way to do this would be to either do the loop straight and subtract the value from 500

int [] aftel = new int [500];
for (int teller3 = 0; teller3 < 500; teller3++){
    aftel500[teller3] = (500 - teller3) + 1;
}

Or do the same to the array index

int [] aftel = new int [500];
for (int teller3 = 500; teller3 > 0; teller3--){
   aftel[500 - teller3] = teller3;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87261&siteId=1