My code to access elements of array using for loop. The output of the program is [19,17,15]
which are the elements of array int a[] = { 12, 15, 16, 17, 19, 23 }
. Output after following code is written:
public class Tester {
public static void main(String s[]) {
int a[] = { 12, 15, 16, 17, 19, 23 };
for (int i = a.length - 1; i > 0; i--) {
if (i % 3 != 0) {
--i;
}
System.out.println(a[i]);
}
}
}
Algorithm:
Iteration 1:
i=5
soa[5]=23
. "if statement" gets true and--i
execute. soi=4
. Hence,a[4]=19
will get print as first element in output.Iteration 2:
i=3
soa[3]=17
. "if statement" gets true again and--i
should execute but it skips that condition as I tried using debugging tool to see how it is working. And output isa[3]=17
which is wrong I think.
Could you help me in understanding why it gives 17 as output? As in my opinion it should skip that part.
CodePudding user response:
Here is a step by step explanation. (i % 3 != 0)
checks to see if i is not divisible by 3
. Also note that in this context, your post and pre-decrements of i
are not relevant as the outcome would be the same no matter how they are decremented.
i = 5;
i not divisible by 3 so i-- = 4
print a[4] = 19
i-- at end of loop = 3
i is divisible by 3 so i remains 3
print a[3] = 17
i-- at end of loop = 2
i not divisible by 3 so i-- = 1
print a[1] = 15
i-- = 0 so loop terminates.
CodePudding user response:
In iteration 2, where i=3 the condition is false, since 3 % 3 = 0