How do I solve a Balanced array problem

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.
Last edited on
On lines 23 and 30 it should be just len, not a[len].

You don't need the checks i%2!=0 because i is even anyway. (You are going up from 0 in steps of 2.)
Similarly, you don't need the check j%2==0.

isBal declared on line 6 is unused.

Variable i declared on line 8 is also unused. (Another variable - also named i! - comes into scope on line 12.)

You would also be entitled to return 0 as soon as you found an imbalance, not continue checking the rest.
Last edited on
Fantastic!!! It works perfectly. @lastchance Thanks a lot, you even optimized my code like some kind of compiler picking up on all the unused variables and stuff. Hope you won't mind I chat you in private when I have issues as I am just a bit above beginner level and I am preparing for some online test. I kind of have a whole lot of practice exercises to solve on functions and arrays like the one above. Thanks again.
CollinsLainzo wrote:
you even optimized my code like some kind of compiler picking up on all the unused variables


Err, have to confess, ... I just used cpp.shell, the forum compiler (click the gear wheel to the top-right of the code sample). It picked up the majority of issues.

Best to put all correspondence in the open forum. You will get more and probably better replies.
Topic archived. No new replies allowed.