Java program to calculate sum of even and odd numbers in an array

Let’s learn java program to calculate sum of even and odd numbers in an array.

Java program to calculate sum of even and odd numbers in an array

In the previous post we discussed how to calculate even and odd numbers in an array.

Now in this post let’s calculate sum of even and odd numbers in an array.

Here’s java program.

import java.util.Scanner;
public class FindSumOf
{
   public static void main(String[] args)
   {
      int number, sumEven = 0, sumOdd = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of elements in an array: ");
      number = sc.nextInt();
      int[] arrNumbers = new int[number];
      System.out.println("Please enter elements of the array: ");
      for(int a = 0; a < number; a++)
      {
         arrNumbers[a] = sc.nextInt();
      }
      for(int a = 0; a < number; a++)
      {
         if(arrNumbers[a] % 2 == 0)
         {
            sumEven = sumEven + arrNumbers[a];
         }
         else
         {
            sumOdd = sumOdd + arrNumbers[a];
         }
      }
      System.out.println("Sum of even numbers in an array: " + sumEven);
      System.out.println("Sum of odd numbers in an array : " + sumOdd);
      sc.close();
   }
}


Output:

Please enter number of elements in an array: 8
Please enter elements of the array:
1
2
3
4
5
6
7
8
Sum of even numbers in an array: 20
Sum of odd numbers in an array : 16


Also read – nested classes in java