Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]+" ");
    }
like image 997
Hoogland Avatar asked Jan 18 '26 03:01

Hoogland


1 Answers

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;
}
like image 101
Federico klez Culloca Avatar answered Jan 20 '26 18:01

Federico klez Culloca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!