Sum of Even and Odd Numbers in Array in Java

Program description:- Write a Java program to find the sum of even and odd numbers in an array. Display the sum value.

Example1:-
Array = {11, 12, 13, 14, 15}
Odd numbers sum = 39
Even numbers sum = 26

Example2:-
Array = {-15, -10, -5, 0, 5, 10, 15}
Odd numbers sum:- 0
Even numbers sum:- 0

Prerequisite:- Array in Java, find length of array in Java

In this program, we will take input value for the array from the end-user, but you can take it explicitly. See:- how to take array input in Java. We will use a method to perform the operation. 

Procedure to find the sum of even and odd numbers in Java array,
a) Take an array.
b) Take two variables to store the sum of even and odd numbers. Assume they are evenSum, and oddSum. Initialize them with 0.
c) Traverse the array.
d) Check each element of the array.
e) If the element is an even number then add it to evenSum.
f) Else add it to oddSum.
g) Display evenSum, and oddSum values.

Java Program to Find Sum of Even and Odd Numbers in given Array

import java.util.Arrays;
import java.util.Scanner;

public class ArrayTest {

  public static void main(String[] args) {
    // create Scanner class object to take input
    Scanner scan = new Scanner(System.in);

    // read size of the array
    System.out.print("Enter size of the array: ");
    int n = scan.nextInt();

    // create an int array of size n
    int numbers[] = new int[n];

    // take input for the array
    System.out.println("Enter array elements: ");
    for (int i = 0; i < n; ++i) {
      numbers[i] = scan.nextInt();
    }

    // find of odd and even
    oddEvenSum(numbers);

    // close Scanner
    scan.close();

  }

  // method to find sum of even-odd in array
  public static void oddEvenSum(int[] numbers) {

    // variables
    int oddSum = 0;
    int evenSum = 0;

    // check each element and add 
    for (int num : numbers) {
      if (num % 2 == 0) { // even
        evenSum += num;
      } else {            // odd
        oddSum += num;
      }
    }

    // display resultant values
    System.out.println("Odd numbers sum = " + oddSum);
    System.out.println("Even numbers sum = " + evenSum);
  }
}

Output:-

Enter the size of the array: 5
Enter array elements:
11 12 13 14 15
Odd numbers sum = 39
Even numbers sum = 26

Enter the size of the array: 7
Enter array elements:
9 8 7 6 5 4 3
Odd numbers sum = 24
Even numbers sum = 18

Also see:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *