QUESTION:
Write a function that takes an array of integers as an argument and returns a value based on the sums of the even and odd numbers in the array. Let X = the sum of the odd numbers in the array and let Y = the sum of the even numbers. The function should return X-Y
The signature of the function is: int f(int [] a)
Examples
if input array is | return |
---|---|
{1} | 1 |
{1, 2} | -1 |
{1, 2, 3} | 2 |
{1, 2, 3, 4} | -2 |
{3, 3, 4, 4} | -2 |
{3, 2, 3, 4} | 0 |
{4, 1, 2, 3} | -2 |
{1, 1} | 2 |
{} | 0 |
ANSWER:
import java.util.*;
public class ArraySum {
public int f(int[] a) {
int X = 0; // initialization for sum of odd numbers in an array
int Y = 0; // initialization for sum of even numbers in an array
for(int i = 0; i<a.length; i++) {
if(a[i] % 2 == 1) {
X+=a[i];
}
if(a[i] % 2 == 0) {
Y+=a[i];
}
}
return X-Y;
}
public static void main(String[] args) {
ArraySum obj = new ArraySum();
int [] A = {1};
int [] B = {1, 2};
int [] C = {1, 2, 3};
int [] D = {1, 2, 3, 4};
int [] E = {3, 3, 4, 4};
int [] F = {3, 2, 3, 4};
int [] G = {4, 1, 2, 3};
int [] H = {1, 1};
int [] I = {};
// Printing results on the screen
System.out.println("Result for array A "+Arrays.toString(A)+" is "+obj.f(A));
System.out.println("Result for array B "+Arrays.toString(B)+" is "+obj.f(B));
System.out.println("Result for array C "+Arrays.toString(C)+" is "+obj.f(C));
System.out.println("Result for array D "+Arrays.toString(D)+" is "+obj.f(D));
System.out.println("Result for array E "+Arrays.toString(E)+" is "+obj.f(E));
System.out.println("Result for array F "+Arrays.toString(F)+" is "+obj.f(F));
System.out.println("Result for array G "+Arrays.toString(G)+" is "+obj.f(G));
System.out.println("Result for array H "+Arrays.toString(H)+" is "+obj.f(H));
System.out.println("Result for array I "+Arrays.toString(I)+" is "+obj.f(I));
}
}
OUTPUT:
Result for array A [1] is 1
Result for array B [1, 2] is -1
Result for array C [1, 2, 3] is 2
Result for array D [1, 2, 3, 4] is -2
Result for array E [3, 3, 4, 4] is -2
Result for array F [3, 2, 3, 4] is 0
Result for array G [4, 1, 2, 3] is -2
Result for array H [1, 1] is 2
Result for array I [] is 0
That's one of examples in java arrays that can improve your reasoning, practice as many challenges as you can to better your programming skills. Thank you for taking time to read through this post.
Top comments (1)
And for those interested in the one liner, more functional approach :
return Arrays.stream(a).reduce(0, (partial, i) -> i%2==0?partial-i:partial+i);