# Sum of the even numbers in an array?

Page 1 of 1

## 3 Replies - 31746 Views - Last Post: 10 November 2008 - 09:53 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=71349&amp;s=ae48b5cdd8148ade0adcedf0961ffde9&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 EricFG

Reputation: 1
• Posts: 7
• Joined: 10-November 08

# Sum of the even numbers in an array?

Posted 10 November 2008 - 09:42 PM

I am trying to sum up the even numbers in my array, but I am not sure what I am doing wrong. I know I need to use "%2" somewhere, but am completely lost. I searched the forums, but all examples were in C++ and not C. Any help would be appreciated. Thanks.

```void sum(const int array[], int count)

{

int i;
int sum = 0;

for (i = 0; i < count; i++){
if(i % 2 == count)
sum = sum  + array[i];

}
printf("The sum of the even numbers in the array is - %d",sum);
printf("\n\n");

}

```

This post has been edited by EricFG: 10 November 2008 - 09:44 PM

Is This A Good Question/Topic? 0

## Replies To: Sum of the even numbers in an array?

### #2 KYA

• Wubba lubba dub dub!

Reputation: 3202
• Posts: 19,232
• Joined: 14-September 07

## Re: Sum of the even numbers in an array?

Posted 10 November 2008 - 09:45 PM

The question is:

do you want to sum up the numbers located at the even subscripts in your array?

or

do you want to add all numbers that are even in your array?

First method:

```//stuff

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

```

second

```//stuff
for(int i = 0; i < count; i++)
{
if (arr[i] %2 == 0)
sum += arr[i];
}

```

Hope that helps

### #3 GWatt

Reputation: 307
• Posts: 3,105
• Joined: 01-December 05

## Re: Sum of the even numbers in an array?

Posted 10 November 2008 - 09:45 PM

if (i % 2 == count) you want if (array[i] % 2 == 0)

The % operator gives the remainder of the the left side divided by the right side, and when you divide an even number by 2 the remainder is zero.

edit:
and KYA beat me to the punch

This post has been edited by GWatt: 10 November 2008 - 09:46 PM

### #4 EricFG

Reputation: 1
• Posts: 7
• Joined: 10-November 08

## Re: Sum of the even numbers in an array?

Posted 10 November 2008 - 09:53 PM

thanks so much for the help, been staring at it for hours...such a simple fix.