Reputation: 484
i am trying to get the sum of even numbers from a recursive array and the sum of an odd number and then add both sums together. i am trying to loop through the arrays so that to get the even numbers but it keep return the first index. please help and thanks in advance..
my aim is to take in array 2,1,5,9,8,4 take the even index and add it to the odd indexes. a[0]=2,a[1]=1,a[2]=5, a[3]=9, a[4]=8, a[5]=4. so it would take (2+5+8)-(1+9+4)=1
this is what i got so far i am not familiar with recursive so my code might be off
int calc(int *a, int size)
{
if(size==1 || size==0)
return a[0];
for(int i=0; i<size; i++){
if(i%2==0){
int sum_i = a[i];
int m=calc(a, size-1);
if(m>a[size-1])
return m;
}
}
for(int j=0; j<size; j++){
if(j%2!=0);
int sum_j = a[j];
return sum_j;
}
int sum = a[i] - a[j];
int e = calc(a, size-1);
if(e%2==0)
return e=e+0; //return even
return sum;
}
int main( )
{
int a[6]={1,2,3,5,6,2};
int size = 6;
cout<< calc(a, size)<<endl;
system("pause");
return 0;
}
Upvotes: 0
Views: 4943
Reputation: 12749
You don't need recursion for this?
// calc(): returns sum(a[0], a[2], a[4], ...) - sum(a[1], a[3], a[5], ...)
int calc(int *a, int size)
{
int sum_even_pos = 0;
int sum_odd_pos = 0;
for (int i = 0; i < size; i++)
{
sum_even_pos += a[i];
if (++i < size) sum_odd_pos += a[i];
}
return sum_even_pos - sum_odd_pos;
}
Upvotes: 1