An array is called balanced if its even numbered elements (a[0], a[2], etc.) are even and its odd numbered elements (a[1], a[3], etc.) are odd. Write a function named isBalanced that accepts an array of integers and returns 1 if the array is balanced, otherwise it returns 0. Examples: {2, 3, 6, 7} is balanced since a[0] and a[2] are even, a[1] and a[3] are odd. {6, 7, 2, 3, 12} is balanced since a[0], a[2] and a[4] are even, a[1] and a[3] are odd. {7, 15, 2, 3} is not balanced since a[0] is odd. {16, 6, 2, 3} is not balanced since a[1] is even.
If you are programming in Java or C#, the function signature is
int isBalanced(int[ ] a)
I first try to check if an even index has odd value and if an odd index has even value, if the condition it yes then count variable value is changed to 0 otherwise it will not change the value of count variable and returns its default value. Here is my solution. Is it possible to combine the loops?
public class inxedOddEven {
static int[] n = {0,3,2,5};
static int l = n.length;
public static void main(String[] arr){
System.out.println(isBalanced(n));
}
public static int isBalanced(int[] a){
int count = 1;
for(int i = 0; i<l;i+=2){
if(a[i]%2 != 0){
count = 0;
break;
}
}
for(int j = 1;j< l; j+=2 ){
if(a[j]%2 == 0){
count = 0;
break;
}
}
return count;
}
}