Java program for Sum of even and odd elements in an array
You will be given an array and you need to find odd numbers and add them, find even numbers and add them and print the absolute value of subtraction between those two sums of odd and even values.
Input Format
You will be taking a number as an input from STDIN which tells about the length of the array. On another line, array elements should be there with single space between them.
Sample Test Case :
Input
3
23 22 1
Output
2
Program :
import java.util.*;
public class SumofEvenOddNumbers {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
public class SumofEvenOddNumbers {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
int evenSum = 0, oddSum = 0;
for(int i=0; i<arr.length; i++){
if(arr[i] % 2 == 0)
evenSum = evenSum + arr[i]
else
oddSum = oddSum + arr[i];
}
System.out.print(evenSum>oddSum ? evenSum-oddSum : oddSum-evenSum);
}
}
arr[i] = sc.nextInt();
}
int evenSum = 0, oddSum = 0;
for(int i=0; i<arr.length; i++){
if(arr[i] % 2 == 0)
evenSum = evenSum + arr[i]
else
oddSum = oddSum + arr[i];
}
System.out.print(evenSum>oddSum ? evenSum-oddSum : oddSum-evenSum);
}
}
Output :
Enter n : 3
Enter array elements : 23 22 1
absolute value of subtraction : 2