[Solved] Even and positive elements in a array c [closed]


This is a corrected version of your code.

int add(int n, int a[10]) {
    if (n < 0) return 0;
    if (a[n] % 2 == 0 && a[n] > 0) return a[n] + add(n-1, a);
    else return add(n-1, a);
}

Note that the correct way to call the function for an array of length 10 is add(9, a); (ie: one less than the length).

Here’s how I would write the code:

int add(const int *a, size_t a_len) {
    int sum = 0;
    for (size_t i = 0; i < a_len; i++)
        if (a[i] % 2 == 0 && a[i] > 0) sum += a[i];
    return sum;
 }

It’s a lot easier to understand, it follows the standard C convention of passing in the length (rather than the length minus 1), uses size_t rather than int for the length of the array, and correctly labels the input array as const. I’d guess that it runs faster (although the compiler may figure out how to turn your recursive version into the faster iterative one, especially at higher optimization levels).

2

solved Even and positive elements in a array c [closed]