2

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]);
}
1
  • In the second loop, myabe you intend: (int i = numbers.length; i > 0; i--) Commented Dec 11, 2013 at 15:54

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank! I knew about the Array sizes and index ranges but I completely forgot to take it into account for my code. Netbeans didnt show me any error either, nor did java when I ran it. I've actually done this exercise before (but left the code somewhere else) and had no issues that time. Very frustrating to have them now! I did not know about the conditions.
@YoNuevo I believe it is more important to understand why the conditions are like this. If you understand how a for cycle works it will be way easier for you to debug your own code.
1

It should be

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

in your reverse order loop.

3 Comments

Please take another look at the cycle. There is one more error that will prevent it from running correctly.
I did forget about the '-1' but I've added it to the code now and it still doesn't print anything. I dont understand why this program is ignoring this piece of code. It doesnt show my any error either.
@YoNuevo take a look at my answer you should also replace i==0 with i >= 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.