Hello guys,
So I have this problem: "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. The function signature should be int isBalanced(int[ ] a).
and I have this solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
using namespace std;
int isBalanced(int a[], int len);
int main()
{
int isBal=1;
int balArr[50];
int size, i;
cout<<"Enter array size: "<<endl;
cin>>size;
cout<<"Enter Array Elements: "<<endl;
for(int i=0; i<size; i++)
{
cin>>balArr[i];
}
cout<<isBalanced(balArr,size);
}
int isBalanced(int a[], int len)
{
int isBalanced =1;
for(int i=0; i<a[len]; i+=2)
{
if((a[i]%2!=0)||(i%2!=0))
{
isBalanced=0;
}
}
for(int j=1; j<a[len]; j+=2)
{
if((a[j]%2==0)||(j%2==0))
{
isBalanced=0;
}
}
return isBalanced;
}
|
Problem is, it only works for the first example and not for all. I need some support.