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.
i = 3
, theni % 3
is0
. That would mean your if statement becomes false and not true.if
statement doesn't checka[i] % 3 != 0
- it checksi % 3 != 0
. In the first iterationi
is 5 andi % 3 != 0
is true. In the second iterationi
is 3 andi % 3 != 0
is false and thereforei
is not decremented anda[3]
gets printed.a%b
is the modulo operator. It returns the reminder ofa/b
i
twice (once as a result of the condition and again as an an unconditional part of your forloop). Instead replace theif
body withcontinue
.