How the same code results in two answers? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

6th Jun 2019, 8:38 AM
Heisenberg
Heisenberg - avatar
3 Answers
+ 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!
6th Jun 2019, 9:02 AM
777
777 - avatar
+ 10
Because it's not the same code.
6th Jun 2019, 9:32 AM
Sonic
Sonic - avatar
+ 1
Thanks everyone 😅😅😅 My negligence
6th Jun 2019, 9:39 AM
Heisenberg
Heisenberg - avatar