java array sum ....query | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

java array sum ....query

i was programming in java and i found the following 2 codes give the same output: why? class Myclass{ public static void main(String[] args){ int [] myarr={1,2,3,4,5,6,7,8,9,10}; int sum=0; for(int x=0;x<myarr.length;x++){ sum+=myarr[x]; } System.out.println(sum); } } class Myclass{ public static void main(String[] args){ int [] myarr={1,2,3,4,5,6,7,8,9,10}; int sum=0; for(int x=0;x<=myarr.length;x++){ sum+=x;

30th Mar 2018, 5:34 PM
Amitesh Shrey
Amitesh Shrey - avatar
3 Antworten
+ 1
https://www.sololearn.com/Codes/ ^Post your codes there and link us. Posts in the 'Discuss' area is limited by a certain amount of characters, which is why your post got cut off half-way through. However, to answer your question, it appears that it's because you're adding together the exact same numbers. In your array, it's 1-10 that's being added together. In your loop, x is iterating from 0-10 and adding the numbers together, which is the exact same numbers as 1-10. That's why you get same output; coincidence that it's the same numbers. Change one number in the array and it won't be the same.
30th Mar 2018, 5:41 PM
Fata1 Err0r
Fata1 Err0r - avatar
0
on the first class: sum = sum + myarr[x] 1 = 0 + myarr[0] 3 = 1 + myarr[1] 6 = 3 + myarr[2] ...and so on on the secon class: sum = sum + x 1 = 0 + 1 3 = 1 + 2 6 = 3 + 3 and so on...
30th Mar 2018, 5:52 PM
Heji Palaña
Heji Palaña - avatar
0
thanks for letting me know !
31st Mar 2018, 4:33 AM
Amitesh Shrey
Amitesh Shrey - avatar