K Jeffreys K Jeffreys - 16 days ago 5
Java Question

for loop math with array in java

I'm trying to practice using Arrays methods in java. I used the following code to make an Java array:

int numArr[] = new int[10];

for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}


My intention was to use this to make the list 20,18,...,4,2. Then, I wanted to use the Arrays sort method to see if it worked properly.

The odd result that I can't understand is that above code prints:

numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 10;
numArr[i] = 8;
numArr[i] = 6;
numArr[i] = 4;
numArr[i] = 2;


I understand the simple mistake with printing the i each time but I don't understand why the initial results are all the 0. I thought maybe it just failed and they were still just initialized to the 0 default. But then I realized that after later in the code after using Arrays.sort(), the list prints correctly for all of the indexes 2,4,...,18,20.

What mistake am I making on the pre-sorted array print?

Answer

Your mistake is in how you are indexing into the array in the loop. You are assigning to array element (numArr.length)-i-1 but printing array element i. Try printing array element (numArr.length)-i-1 inside the loop to see the value you just assigned.