ThatBoy123
ThatBoy123

Reputation: 77

Returning and Summing the Odd Numbers of an Array

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; 
                    }
            }

Upvotes: 1

Views: 1579

Answers (3)

Running24
Running24

Reputation: 100

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.

Upvotes: 3

WJS
WJS

Reputation: 40072

And a Java 8+ solution would be

  public static int sumOdds(int[] numbers) {
      return Arrays.stream(numbers).filter(n -> n % 2 == 1).sum();
  }

Upvotes: 1

Matthew Formosa
Matthew Formosa

Reputation: 468

There are a few issues here. First of all, the mod operation is not going to work on an array. It needs to be performed on a single number. Furthermore, you are immediately returning the sumOdds without allowing the entire loop to complete.

This would work.

public static int sumOdds(final int[] numbers) {
    int sumOdds = 0;
    for (int number : numbers) {
        if (number % 2 != 0) {
            sumOdds += number;
        }
    }
    return sumOdds;
}

Or better yet, use streams.

int sumOdds = IntStream.of(12, 6, 7, 15, 1).filter(number -> number % 2 != 0).sum()

Upvotes: -1

Related Questions