Skip to content
Advertisement

Create array which stores odds from -6 to 38 in java

I’m learning Java and I found an exercise which I can’t solve, in the Arrays chapter.

The exercise says:

Write code that creates an array named odds and stores all odd numbers between -6 and 38 into it using a for loop. Make the array’s size exactly large enough to store the numbers.

The only solution I could come up with is this:

JavaScript

However, the program prints:

JavaScript

And I don’t understand why.

Advertisement

Answer

You don’t need nested FOR loops here. Just create an integer variable i to track your position in the array and increment it when adding each new item. PS… the array should have been called “odds” based on the specs of the assignment. I suggest renaming that variable you were using to count the number of odds to something else (e.g. numberOfOdds)

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement