How do I create a function that has an array of integers and the arrays length as parameters that will return true if the sum of the array elements is even and false otherwise?
How would I do this without using any static variables?
CodePudding user response:
I wrote 2 versions, one with recursion, other with no recursion
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int[] arr={5, 3, 1};
System.out.println("sum of " Arrays.toString(arr) " is " size_ispair_rec(arr, arr.length));
}
public static boolean size_ispair_rec(int[] arr, int size){
if(size-1 == 0){
return arr[size]%2==0;
}
return !((arr[size-1]%2 == 0) ^ size_ispair_rec(arr, size-1));
}
public static boolean size_ispair(int[] arr, int size){
int sum=0;
for(int i=0; i<size; i){
sum =arr[i];
}
return sum%2 == 0 ? true : false;
}
}
CodePudding user response:
Here is a recursive method that does the job. I've tried to keep the code readable.
The idea is that the only time you get an even number by addition is when
- Both the numbers are even
- Both the numbers are odd
At every recursive call, we check if adding the number to the previous calculated value makes it even or odd.
public static boolean isSumEven(int arr[], int length){
if(length == 0){
return true;
} else {
boolean sumPreviousElemsEven = isSumEven(arr, length - 1);
boolean currentElemEven = arr[length-1]%2 == 0 ? true : false;
if(sumPreviousElemsEven && currentElemEven || !sumPreviousElemsEven && !currentElemEven){
return true;
} else {
return false;
}
}
}