+ 4

Array in Java and Sum

int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; ++x) { why output is 58? we have "++x" - the step should start from 1 ! And the first elements of array is "42". The result should be 52!

29th Jan 2018, 9:45 PM
Grey King
Grey  King - avatar
9 Answers
+ 9
Your for loop: for(int x=0; x<myArr.length; ++x) is the same as: int x=0; while (x<myArr.length) { // existing for loop code ++x; } so the increment only changes x after the first execution of the loop.
29th Jan 2018, 9:53 PM
John Wells
John Wells - avatar
+ 8
You're welcome. Do you understand now why ++x and x++ does the same thing?
29th Jan 2018, 9:57 PM
John Wells
John Wells - avatar
+ 7
Sorry Grey for not further explaining, I just woke up Iand I had to go to shower. No problems, I learnt this in school just last Friday.
29th Jan 2018, 10:04 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 6
No start from 0!!
29th Jan 2018, 9:48 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 5
yes in the loop it no deference? In any case?
29th Jan 2018, 9:58 PM
Grey King
Grey  King - avatar
+ 4
Thank you John! Your answer was the maximum understandable! :)
29th Jan 2018, 9:56 PM
Grey King
Grey  King - avatar
+ 3
answer "58" should be if step is "x++"! Help guy's!
29th Jan 2018, 9:46 PM
Grey King
Grey  King - avatar
+ 3
what you mean ? I don't understand why the metod always start from "0" if we have different step "x++" and "++x"?
29th Jan 2018, 9:49 PM
Grey King
Grey  King - avatar
+ 3
all fine :) thanks for your helping guy's
29th Jan 2018, 10:05 PM
Grey King
Grey  King - avatar