+ 3
How the same code results in two answers?
int[] a = {100, 89, 6, 3}; for (int i = 1; i < a.length; i++) { a[i]=a[i-1] % a[i]; System.out.println (a[i]); } Output: 11 5 2 int[] a = {100, 89, 6, 3}; for (int i = 1; i < a.length; i++) { System.out.println ( a[i-1] % a[i]); } Output: 11 5 0 I don't get it!!! 6%3 results in 0 but the 1st code gives me output 2!! But the second one gives the correct output!! Edit : I got it 😅 It was my negligence Thanks everyone for the answers
3 ответов
+ 3
Notice carefully.
In the first loop, you're modifying the elements here,
a[i]=a[i-1] % a[i];
In the first run, i = 1:
a[1] = a[0] % a[1] => a[1] = 100 % 89 = 11
So, a = { 100, 11, 6, 3 }
In the second run, i = 2:
a[2] = a[1] % a[2] => a[2] = 11 % 6 = 5
So, a = { 100, 11, 5, 3 }
Lastly, in the third run, i = 3:
a[3] = a[2] % a[3] => a[2] = 5 % 3 = 2
which explains your first output ;)
While in the second code, you aren't assigning!
+ 10
Because it's not the same code.
+ 1
Thanks everyone 😅😅😅
My negligence