YoNuevo
YoNuevo

Reputation: 117

printing an array with a for-loop

I've build an array with 10 plurals of 7 and am now trying to print it in reversed order with a for loop. but my program seems to be ignoring this code. I've no issues printing it in regular order with a for or a for each loop. What is wrong in this piece of code?

int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++) {
     numbers[i] = (int) (Math.random() * 10) * 7;
}
for (int i = numbers.length; i == 0; i--) {
     System.out.println(numbers[i]);
}
System.out.println("---");
for (int i = 0; i < numbers.length; i++) {
     System.out.println(numbers[i]);
}

Upvotes: 2

Views: 152

Answers (2)

zavg
zavg

Reputation: 11061

It should be

for (int i = numbers.length - 1; i >= 0; i--) {

in your reverse order loop.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

An array of size N in java has its indexes ranging from 0 to N-1. So in fact numbers.length is out of bounds - the last element in numbers is with index numbers.length - 1. Also not your condition should be i >= 0 instead of i==0, otherwise your cycle will never be executed for an array of size greater than 1.

Upvotes: 3

Related Questions