Programming Examples

Java program to accept n elements in array and find the sum of even and odd elements


Write a Java program which accept n integer from user and find the sum of Even and Sum of Odd Elements.

Solution:

import java.util.*;
class SumEvenOdd
{
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);        
        System.out.println("Enter the size of Array : ");
        int n=sc.nextInt();
        int num[]=new int[n];        
        int sum_even=0,sum_odd=0;
        System.out.println("Enter the "+n+" Elements of Array");
        for(int i=0;i<n;i++)
        {
            num[i]=sc.nextInt();
        }
        for(int i=0;i<n;i++)
        {
            if(num[i]%2==0)
            {
                sum_even=sum_even+num[i];
            }
            else
            {
                sum_odd=sum_odd+num[i];
            }            
        }
        System.out.println("Sum of Even Elements :"+sum_even);
        System.out.println("Sum of Odd Elements :"+sum_odd);
    }
}
Output

Enter the size of Array : 

5

Enter the 5 Elements of Array

3

4

5

6

7

Sum of Even Elements :10

Sum of Odd Elements :15

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz