# Sum all odd array elements?

• 11-04-2008
Marth_01
Sum all odd array elements?
I was wondering how one would sum up all of the even elements of an array into one sum and all of the odd elements of an array into another.

Let's say the array is "double a[]" and the size is "n".

I could first have to figure out if the array is either even or odd by doing a "&#37;2 == 0" IF statement, but I don't know if that is necessary.

I'm guessing there could be two possible for loops with something in them like "a[n+2]" to skip every other value, and only go to as many values as the IF statement would retrieve.

The details are a bit fuzzy for me to think out logically, on paper, or in C. If someone could tell me a basic run down of how I should go about doing it or a for loop or two written out showing me how to skip odd/even values in an array that would be awesome.
• 11-04-2008
tabstop
If the details are fuzzy, there's nothing you can do but write things out on a piece of paper until they're clear. I can think of five different ways to do this off the top of my head, so you're going to have to decide what you want to do.
• 11-04-2008
Marth_01
Yeah, writing things out on paper usually works pretty well for me, but sometimes I just get stumped. I know I want to do it with a for loop, but I don't know the correct way to write it. I'm not that great on pointing out what is or isn't legal. I'd like to write:

for( 1st even number in array; 1st even number until max value in array; add two to array, skipping the odd number)

add that value to a separate value called even sum
• 11-04-2008
tabstop
Hopefully you know what the 1st even number in the array is. The constraint of even number in the second part is useless. The third part is redundant, as adding two to array (I assume you mean the array index) by definition skips the odd number.
• 11-04-2008
Marth_01
How do you say the value that an array has rather than the number of the array it is?

IE. a[100] means an array from 0~99, but how do you say the last element?

It wouldnt be a[99] because that would mean creating an array from 0~98 right?
• 11-04-2008
tabstop
If you say int a[100]; then a[0] is the first element and a[99] is the last.
• 11-04-2008
Marth_01
tabstop you are awesome, one last question: how do you make it skip the next element in the array? "a[x+2]" for example, or would it be "a[x] + 2", or something else?
• 11-04-2008
tabstop
Obviously you would add two to the index, not to the number being held in the array itself.
• 11-04-2008
Marth_01
Code:

```int x = 0; for (a[x]; a[x] <= a[n]; a[x+2]) { *even_sum += a[x] } int x = 1; for (a[x]; a[x] <= a[n]; a[x+2]) { *odd_sum += a[x] }```
Why is it giving me parse errors before the ")" in the for loops? Should work...
• 11-04-2008
tabstop
Because even single statements need to end in semicolons. Also note that "a[x+2]" is an empty statement -- it doesn't change x. You need to assign a new value to x here.