+ 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;
3 odpowiedzi
+ 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.
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...
0
thanks for letting me know !