I'm trying to add all the odd numbers in an array and return it. Any thoughts on what I'm doing wrong?
Example:
Input:
Array- [12,6,7,15,1]
It would return 23
public static int sumOdds(int[] numbers) {
sum = 0;
for(int i = 0; i < numbers.length; i++) {
if (numbers%2==0)
return 0;
else (numbers[i] % 2 != 0) {
sum += numbers;
return sumOdds;
}
}
public static int sumOdds(int[] numbers) {
int sum = 0;
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
return sum;
}
This should work. return
statements should not be within your if
and else
statements, as they will end the execution of the program immediately.