Skip to content
Advertisement

Need to find even sums of digits in the array

I need to find even sum of digits from an array in Java.

Array: int [] cars = {3, 4, 6, 5};

Output: 8 10

Process:

3 + 4 == 7 –> not even

3 + 6 == 9 –> not even

3 + 5 == 8 –> even (so print it)

4 + 6 == 10 –> even (so print it)

4 + 5 == 9 –> not even

6 + 5 == 11 –> not even

Advertisement

Answer

If this is to check two value combination, you can use something like the below,

    int[] arr = {1, 2, 3, 4, 5, 6};
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if ((arr[i] + arr[j]) % 2 == 0) {
                System.out.println("" + arr[i] + "+" + arr[j] + "=even");
            } else {
                System.out.println("" + arr[i] + "+" + arr[j] + "=odd");
            }
        }
    }

and the output will look like this

1+2=odd
1+3=even
1+4=odd
1+5=even
1+6=odd
2+3=odd
2+4=even
2+5=odd
2+6=even
3+4=odd
3+5=even
3+6=odd
4+5=odd
4+6=even
5+6=odd
Advertisement