0

Please explain this code....

public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }

30th Sep 2019, 8:27 AM
Priyanka Gotugade.
Priyanka Gotugade. - avatar
2 Answers
+ 5
You should focus on x's values in the for loop on this line: for (int x=0; x<myArr.length; x++) {} We know that myArr.length is 4, thus we can short it a little: for (int x=0; x<4; x++) {} These 3 statements say: In the beginning x gets value 0. Loop will continue iterating as long as x < 4 is true. x gets incremented by 1 in each iteration. We can conclude, that the loop breaks when x equals 4 and thus the loop will iterate 4 times for: x=0, x=1, x=2 & x=3. In program it's not profitable to do so, but we could split the for loop to: int x; x = 0; sum += myArr[x]; x = 1; sum += myArr[x]; x = 2; sum += myArr[x]; x = 3; sum += myArr[x]; And: sum += myArr[0]; sum += myArr[1]; sum += myArr[2]; sum += myArr[3]; We know what are in myArr indices 0, 1, 2 and 3. So we can minimize previous clip a little more. sum += 6; sum += 42; sum += 3; sum += 7; Thus in the end sum will be: sum = 6 + 42 + 3 + 7; And thus sum = 58.
30th Sep 2019, 9:11 AM
Seb TheS
Seb TheS - avatar
+ 5
Seb TheS wow, that's a nice explanation👏👏👌
30th Sep 2019, 9:12 AM
Farhan
Farhan - avatar