Reputation: 15
Write a function that takes an array as input and returns an array of 2 numbers. The returned array contains the sum of even numbers and sum of odd numbers from the input.
If any of the input is null it should be treated as an empty array
Example: Input:
[30, 18, 2, 83, 20, 71]
Output:
[70, 154]Input:
[14, 11, 10, 67, 41]
Output:
[24, 119]Input: [36, 24, -82, 29, 44, -3, -100, -5, 49] Output: [-78, 70]
The function that I have written is
public int[] getSumOfEvensAndOdds(int[] input) {
int x[] = input;
int even = 0, odd = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] % 2 == 0)
even += x[i];
else
odd += x[i];
}
int[] ans={even, odd};
return ans;
}
But how should I incorporate the part of the empty array?
Upvotes: 1
Views: 15519
Reputation: 239
public int[] getSumOfEvensAndOdds(int[] input) {
int x[] = input;
int even = 0, odd = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] != null) //in case array contains elements which aren't null
{
if (x[i] % 2 == 0)
even += x[i];
else
odd += x[i];
}
else //in case the array has null array elements
{
even = 0;
odd = 0;
}
int[] ans={even, odd};
return ans;
}
Upvotes: 0
Reputation: 47
You need something like this:
public class Test {
public static int[] getSumOfEvensAndOdds(int[] input) {
int[] def = {0,0};
if (input != null && input.length!=0) {
int x[] = input;
int even = 0, odd = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] % 2 == 0)
even += x[i];
else
odd += x[i];
}
int[] ans = {even, odd};
return ans;
}
return def;
}
public static void main(String [ ] args){
int[] ar = {10,20,30,40,50,60,71,80,90,91};
int[] res;
res = getSumOfEvensAndOdds(ar);
System.out.println("Result: " + res[0] + " " + res[1]);
int[] ar2 = {};
res = getSumOfEvensAndOdds(ar2);
System.out.println("Result: " + res[0] + " " + res[1]);
int[] ar3 = null;
res = getSumOfEvensAndOdds(ar3);
System.out.println("Result: " + res[0] + " " + res[1]);
}
}
I use input!=null to check whether the array is null and input.length!=0 to check if its size is 0. Also, in the main method I give three examples.
Upvotes: 0
Reputation:
if any of the input is null it should be treated as an empty array
Why not just check for null
value?
public int[] getSumOfEvensAndOdds(int[] input) {
int even = 0, odd = 0;
if(null != input){
for (int i: input) {
if (0 == i % 2){
even += i;
} else{
odd += i;
}
}
}
return new int[]{even, odd};
}
Upvotes: 2
Reputation: 455
Your question is just about arrays being empty. A quick search got me this: How can I check whether an array is null / empty?
Upvotes: -1
Reputation: 43728
Check if input
is null
first. If it is, work on an empty array instead:
int x[] = input == null ? new int[0] : input;
Upvotes: 4