-1

This is my code:

    int[] p = {1,2,3,4,5};

    System.out.print("Even numbers: ");
    for (int i = 0; i < p.length; i++) {

        if (p[i] == 0) {
        } else if (p[i] % 2 == 0) {
            System.out.print(p[i] + " ");
        }

    }

    System.out.print("\nOdd numbers: ");
    for (int i = 0; i < p.length; i++) {
        if (p[i] % 2 != 0) {
            System.out.print(p[i] + " ");
        }
    }

This program prints:

Even numbers: 2 4
Odd numbers: 1 3 5

Next I want to change my code to print something like this:

Even numbers: 2
Odd numbers: 3

This would mean that I want to print the number of even and odd intigers in the array.

How do I do this?

  • 2
    http://stackoverflow.com/questions/31769091/java-trying-to-number-printed-items-in-an-if-statement – assylias Nov 06 '15 at 15:52

2 Answers2

1

just keep a counter

int[] p = {1,2,3,4,5};
int oddCount=0;
int evenCount=0;

    System.out.print("Even numbers: ");
    for (int i = 0; i < p.length; i++) {

        if (p[i] == 0) {
        } else if (p[i] % 2 == 0) {
            System.out.print(p[i] + " ");
            evenCount++;
        }

    }

    System.out.println("Evencount"+evenCount);

    System.out.print("\nOdd numbers: ");
    for (int i = 0; i < p.length; i++) {
        if (p[i] % 2 != 0) {
            System.out.print(p[i] + " ");
            oddCount++;
        }
    }

    System.out.println("Odd count"+oddCount);
AbtPst
  • 7,778
  • 17
  • 91
  • 172
0
class Test
{
    public static void main(String args[])
    {
    int noEven=0;
    int noOdd=0;
    int[] p = {1,2,3,4,5};
    System.out.print("Even numbers: ");
    for (int i = 0; i < p.length; i++) {

        if (p[i] == 0) {
        } else if (p[i] % 2 == 0) {
            //System.out.print(p[i] + " ");
            noEven++;
        }

    }
    System.out.println(noEven);

    System.out.print("\nOdd numbers: ");
    for (int i = 0; i < p.length; i++) {
        if (p[i] % 2 != 0) {
            //System.out.print(p[i] + " ");
            noOdd++;
        }
    }
    System.out.println(noOdd);
}
}
ABHISHEK RANA
  • 333
  • 3
  • 7