Results 1 to 6 of 6
  1. #1
    frasifrasi is offline Member
    Join Date
    Jun 2008
    Posts
    20
    Rep Power
    0

    Default 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?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    cross-posted in the Sun Java forums.

  3. #3
    sukatoa's Avatar
    sukatoa is offline Senior Member
    Join Date
    Jan 2008
    Location
    Cebu City, Philippines
    Posts
    556
    Rep Power
    7

    Default

    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,
    Java 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 "+="
    Last edited by sukatoa; 06-09-2008 at 07:31 AM.
    freedom exists in the world of ideas

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Hope you are looking something like this.

    Java 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);
        }

  5. #5
    frasifrasi is offline Member
    Join Date
    Jun 2008
    Posts
    20
    Rep Power
    0

    Default

    ^ Yes, very simple. Thank you for the insight.

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •