user6913230 user6913230 - 1 month ago 9
C Question

A for loop that calculates the even or odd then adds them up

Hi there I am writing a program that is meant to take the numbers stored in an array and if they are even, add them up. However I keep running into this error


"main.c:9:16: warning: comparison between pointer and integer [enabled by default]


for (i = 0; i < MAX_LEN; ++i){



This is my program here I dont know if it will calculate properly or not, as I have never been able to successfully run it. Thanks for any help

#include <stdio.h>

int main() {
int MAX_LEN[15] = {10,12,52,131,15,84,3,4,11,14,32,2,1,6,7};
int i = 0;
int sum = 0;

for (i = 0; i < MAX_LEN; ++i){
if (MAX_LEN[i] % 2 == 0){
sum = sum + MAX_LEN[i];
}
else {
sum = sum;
}
}
printf("Sum: %d", sum);
return 0;
}

Answer

Your problem resolved, see the below C code snippet:

#include <stdio.h>

#define MAX_LEN 15U

int main() {
int my_array[MAX_LEN ] = {10,12,52,131,15,84,3,4,11,14,32,2,1,6,7};
int i = 0;
int sum = 0;

for (i = 0; i < MAX_LEN; ++i){
    if (my_array[i] % 2 == 0){
        sum = sum + my_array[i];
    }
    else {
        sum = sum;
    }
}
printf("Sum: %d", sum);
return 0;
}