How to say if (odd)?

• 06-09-2008, 03:47 AM
frasifrasi
How to say if (odd)?
I have an array of 8 numbers. I want to say that if the index of the array is odd, do something.
For example:
add up all numbers int he odd indexes:
array[1]+array[3]+array[5] ...

How would I code this--any suggestions?
• 06-09-2008, 05:25 AM
Fubarable
cross-posted in the Sun Java forums.
• 06-09-2008, 07:21 AM
sukatoa
not clear actually....

What's the purpose of adding up all the value from those elements if your question is to have a logical value that represents odd or not?

You may design a method that returns a logical value true/false with a parameter int value.....

Here is an example,
Code:

```public static final boolean isOdd(int value){       return (value%2)>0; }```
Then, use that for testing those elements if the value is an odd or not....

If satisfied, do the operation....

You may use simplified operator "+="
• 06-09-2008, 01:42 PM
Eranga
Hope you are looking something like this.

Code:

```    public static void main(String[] args) {         // TODO code application logic here         int[] number = new int[8];         number[0] = 1;         int sum  = 0;             // Filled the array with some numbers         for(int i = 1; i < number.length; i++) {             number[i] = number[i - 1] * 2;         }     // Process         for(int j = 0; j < number.length; j++) {             if(j%2 != 0) {                 sum += number[j];             }         }                 System.out.println(sum);     }```
• 06-09-2008, 03:55 PM
frasifrasi
^ Yes, very simple. Thank you for the insight.
• 06-09-2008, 03:59 PM
Eranga
Did you solve this question. If so please mark it as solved.