ift*_*wMZ 0 java arrays for-loop
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++])
Run Code Online (Sandbox Code Playgroud)
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])
Run Code Online (Sandbox Code Playgroud)
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];
}
}
Run Code Online (Sandbox Code Playgroud)
or
int produs = 1;
for (int i = 0; i < arr.length; i = i + 2) {
produs *= arr[i];
}
Run Code Online (Sandbox Code Playgroud)
I am also getting correct answer.
so, my question is why my method with inline for does not work?
int produs = 1;
for (int i = 0; i < arr.length; produs *= arr[i = i + 2])
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)