Java Program to Find the Sum of Even and Odd Numbers

This is a Java Program to Calculate the Sum of Odd & Even Numbers.

Enter the number of elements you want in array. Now enter all the elements you want in that array. We begin from the first element and check if it is odd or even. Hence we add that number into the required addition list dependng whether it is even or odd.

Here is the source code of the Java Program to Calculate the Sum of Odd & Even Numbers. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Sum_Odd_Even 
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, sumE = 0, sumO = 0;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter the number of elements in array:");
  9.         n = s.nextInt();
  10.         int[] a = new int[n];
  11.         System.out.println("Enter the elements of the array:");
  12.         for(int i = 0; i < n; i++)
  13.         {
  14.             a[i] = s.nextInt();
  15.         }
  16.         for(int i = 0; i < n; i++)
  17.         {
  18.             if(a[i] % 2 == 0)
  19.             {
  20.                 sumE = sumE + a[i];
  21.             }
  22.             else
  23.             {
  24.                 sumO = sumO + a[i];
  25.             }
  26.         }
  27.         System.out.println("Sum of Even Numbers:"+sumE);
  28.         System.out.println("Sum of Odd Numbers:"+sumO);
  29.     }
  30. }

Output:

$ javac Sum_Odd_Even.java
$ java Sum_Odd_Even
 
Enter the number of elements in array:6
Enter the elements of the array:
1
3
2
6
7
9
Sum of Even Numbers:8
Sum of Odd Numbers:20

Sanfoundry Global Education & Learning Series -– 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.