a3124
a3124

Reputation: 13

Divide and conquer algorithm that returns the sum of even entries in an array int a[] of size n

I am having some trouble understanding this problem. My code doesn't work, but I don't understand why. My code just keeps going into an infinite loop. I am trying to find all entries in the array that are even numbers, not the indices.

#include <stdio.h>
#include <iostream>
using namespace std;
int sumeven(int arr [6], int left, int right, int n);
int main()
{
    int a[6];
    int left = 0;
    int right = 5;
    int n = 6;
    for (int i = 0; i <6; i ++)
    {
        a[i] =i;
    }
    int result = sumeven(a,left,right,n);
    cout<< "result = " <<result;
    return 0;
}

int sumeven(int a[6], int left, int right, int n)
{
    int m;
    if (left == right)
    {
        if ((a[left]%2) == 0)
        {
            cout<< left;
            return left;
        }
    }
    m = (left+(right))/2;
    return (sumeven(a, left, m, n) + sumeven(a, m+1,right, n));
}

Upvotes: 0

Views: 996

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

In sumeven, if left == right and a[left] % 2 != 0, you call sumeven with the same parameters, thus ensuring your loop never ends.

You need to still terminate the recursion with a[left] is odd with left == right.

Upvotes: 1

Related Questions