0

Please explain this code in simpler terms for me.

int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); // 58

31st Mar 2020, 1:54 PM
Akporue Victory
Akporue Victory - avatar
1 ответ
+ 2
This program first initialzes an array whose name is `myArr`. Then initializes `sum` variable to 0. In for loop during each iteration value of `x` is incremented by 1. From 0 to 4. . Because of condition `x<myArr.length` when x becomes 4 loop brakes and control is transferred to statement immediately after loop. Inside loop `x` is used as index to access each element of array `myArr` one by one. `sum+= myArr[x];` is same as `sum= sum + myArr[x];` This loops adds all the elements to variable `sum`. So finally value of variable `sum` is equal to sum of all elements in array. (6+42+3+7 = 58) If you still don't understand it I'll suggest you to start course from very beginning also check tutorial on official website (https://docs.oracle.com/javase/tutorial/). Don't ignore any concept , try to write code. Just reading is not enough.
31st Mar 2020, 2:12 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar