effeja
effeja

Reputation: 65

Summing only even numbers in an array

After taking ten numbers as input from the user, I want to add up the ones that are evenly divisible by 2.

I am able to get the input from the user, but I'm not sure how to check which numbers are divisible by two, and add only those.

#include <stdio.h>
#include <ctype.h>

int main(void) {
    int i = 0; 
    int val;
    char ch;
    int numbers[10];

    while(i < 10) {

        val = scanf("%d%c", numbers + i, &ch);  

        if(val != 2 || !isspace(ch)) {
            while((ch = getchar()) != '\n')  // discard the invalid input
                ;  
            printf("Error! Entered number is not an integer.\n");
            printf("Please enter an integer again.\n");
            continue;
        }
        ++i;
    }
    printf("%d\n", numbers[0]);
    printf("%d\n", numbers[1]);
    printf("%d\n", numbers[2]);
    printf("%d\n", numbers[3]);
    printf("%d\n", numbers[4]);
    printf("%d\n", numbers[5]);
    printf("%d\n", numbers[6]);
    printf("%d\n", numbers[7]);
    printf("%d\n", numbers[8]);
    printf("%d\n", numbers[9]);

    return 0;
}

Upvotes: 0

Views: 450

Answers (3)

abelenky
abelenky

Reputation: 64692

int main(void)
{
    int i;
    int numbers[10];
    int sum = 0;

    for(i=0; i<10; ++i)
    {
        printf("Enter #%d:\n", i+1);
        scanf("%d", numbers+i);

        if (numbers[i] % 2 == 0) // Then Number is even
        {
            sum += numbers[i];
        }
    }

    printf("The sum of only the even numbers is %d\n", sum);

    getch();
    return 0;
}

Upvotes: 0

Steve Cox
Steve Cox

Reputation: 2007

completely unnecessary optimization

int sum[2]={0};
for(size_t i = 0; i <=9; ++i) sum[numbers[i]&1]+=numbers[i];

Upvotes: 0

Jeff Loughlin
Jeff Loughlin

Reputation: 4174

How about:

int sum = 0;
for (int i = 0; i <= 9; i++)
{
    if (numbers[i] % 2 == 0)
        sum += numbers[i];
}

Upvotes: 4

Related Questions