0

Need your help ASAP! [Java]

When I run my code, instead of getting the sum of odd nums, I get sum of even nums. What am i writing wrong in my code? Please, help me! public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int even = 0, odd = 0; for (int i = 0; i <= arr.length; i++) { if (i % 2 == 0) even += arr[i]; else odd += arr[i]; } System.out.println("Sum of odd nums:" + odd); } }

27th Mar 2020, 4:54 PM
AGirlHasNoName
AGirlHasNoName - avatar
6 Antworten
+ 6
Change these two lines- 1) for (int i = 0; i < arr.length; i++) // <= will give ArrayIndexOutOfBoundException 2) if (arr[i] % 2 == 0)
27th Mar 2020, 5:00 PM
Avinesh
Avinesh - avatar
+ 4
you need to write arr[i] % 2 instead of i % 2. In the code above you were checking whether the indexes were ever or odd, not the actual elements.
27th Mar 2020, 4:59 PM
Airree
Airree - avatar
+ 2
Shouldn't 25 be the answer? 1+3+5+7+9=25 and you are getting that so what do you think is wrong?
27th Mar 2020, 5:18 PM
Avinesh
Avinesh - avatar
+ 1
Thank you both @Airree and @Avinesh <3 I changed my code and it looks like this, but still i get the same result. I'm so newbie and can't even guess what am I doing wrong. public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int even = 0, odd = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] % 2 == 0) even += arr[i]; else odd += arr[i]; } System.out.println("Sum of odd nums:" + odd); } }
27th Mar 2020, 5:12 PM
AGirlHasNoName
AGirlHasNoName - avatar
0
I'm getting 30 :( I'd have no prob if i get 25:/
27th Mar 2020, 5:28 PM
AGirlHasNoName
AGirlHasNoName - avatar
0
It returns 25, I ran my code in a new window. Thanks guys <3 Good luck!
27th Mar 2020, 5:34 PM
AGirlHasNoName
AGirlHasNoName - avatar