Javaarraysprodusofevenpositions
So, for example i have an array: int[] {1,2,3,4,5}. I need to print the product of even positions, 0 position will be considered even, so it will be: 1 * 3 * 5 = 15.
When I am summing an array, I am doing something like this:
int sum = 0;
for (int i = 0; i < arr.length; sum += arr[i++])
and I am receiving the answer correct.
Now, I thought of using the same method for getting the product:
int produs = 1;
for (int i = 0; i < arr.length; produs *= arr[i = i + 2])
int produs = 1;
for (int i = 0; i < arr.length; produs *= arr[i = i + 2])
Here I always get an error. I don't know why, but if I am doing:
int produs = 1;
for (int i = 0; i < arr.length; i++) {
if ( (i & 1) == 0) {
produs *= arr[i];
}
}
or
int produs = 1;
for (int i = 0; i < arr.length; i = i + 2) {
produs *= arr[i];
}
I am also getting correct answer.
so, my question is why my method with inline for does not work?
this one.
回答
If you perform a suffix increment operation, the compiler puts the old value on the stack, e.g.
int[] arr = new int[] { 0, 10, 20, 30 };
int i = 0;
int x = arr[i++]; // x will be 0, i is incremented to 1
On the other hand, if you would use a prefix increment operation, the compiler puts the new value on the stack, e.g.
int[] arr = new int[] { 0, 10, 20, 30 };
int i = 0;
int x = arr[++i]; // x will be 10, i is incremented to 1
Lastly, a variable assignment operation puts the resulting value on the stack, e.g.
int[] arr = new int[] { 0, 10, 20, 30 };
int i = 0;
int x = arr[i = i + 3]; // x will be 30, i is increased by 3
Therefore, if you use arr[i = i + 2] as post-block statement, you actually access the following array elements: 2, 4, 6, yielding an ArrayIndexOutOfBoundsException.
I strongly recommended (also for the sake of readability) that you restructure your algorithm to use the for-block to do the actual calculation and to use the post-block statement to increase the variable i:
for (int i = 0; i < arr.length; i+=2) {
// TODO Calculation
}