Write a java program to remove duplicate elements and calculate the sum of even number in the array

Write a program to read an array, eliminate duplicate elements and calculate the sum of even numbers (values) present in the array.

Input and Output Format:

Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next ‘n’ integers correspond to the elements in the array.

In case there is no even integer in the input array, print no even numbers as output. Else print the sum.

Refer sample output for formatting specifications.

Assume that the maximum number of elements in the array is 20.

Sample Input 1:

4

2

5

1

4

Sample Output 1:

6

Sample Input 2:

3

1

1

1

Sample Output 2:

no even numbers

Java program to remove duplicate elements and calculate the sum of even number in the array

package testCases;

import java.util.Iterator;

import java.util.LinkedHashSet;

import java.util.Scanner;

public class MainJava {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int a[] = new int[n];

for (int i = 0; i < n; i++) {

a[i] = sc.nextInt();

}

System.out.println(sumOfEvenNos(a));

}

public static int sumOfEvenNos(int[] a) {

int sum = 0;

LinkedHashSet<Integer> hm = new LinkedHashSet<Integer>();

for (int i = 0; i < a.length; i++) {

hm.add(a[i]);

}

Iterator<Integer> lm = hm.iterator();

while (lm.hasNext()) {

int b = lm.next();

if (b % 2 == 0)

sum = sum + b;

}

return sum;



}



}

 

 

 

Add a Comment

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

three × 2 =