Home > Software engineering >  Counting odd even and zeros in array java
Counting odd even and zeros in array java

Time:06-11

How can I add the codes to find the zeros in the array of this program? This code can count even and odd. Should I do a different statement, or can I just add another if else statement?

import java.util.Scanner;

public class num
{
   public static void main(String args[]) {
       
       final int NUM_COUNT = 20;
       Scanner in = new Scanner(System.in);
       int i = 0;
       
       int arr[] = new int[NUM_COUNT];
       int even[] = new int[NUM_COUNT];
       int odd[] = new int[NUM_COUNT];
       
       System.out.println("Enter 20 numbers:");
       for (i = 0; i < NUM_COUNT; i  ) {
           arr[i] = in.nextInt();
       }
       
       int eIdx = 0, oIdx = 0;
       for (i = 0; i < NUM_COUNT; i  ) {
           if (arr[i] % 2 == 0)
               even[eIdx  ] = arr[i];
           else
               odd[oIdx  ] = arr[i];
       }
       
       System.out.println("Even Numbers:");
       for (i = 0; i < eIdx; i  ) {
           System.out.print(even[i]   " ");
       }
       
       System.out.println("\nOdd Numbers:");
       for (i = 0; i < oIdx; i  ) {
           System.out.print(odd[i]   " ");
       }
   }
}

CodePudding user response:

No need to create extra arrays. Counting can be done with just one integer.

int zeroCount = 0;
for (i = 0; i < NUM_COUNT; i  ) {
    if (arr[i] == 0) {
        zeroCount  ;
    }
}
System.out.println("Zeros: "   zeroCount);

I've changed the output style to clearly label what is being output here. Something to consider for the rest of the code.

CodePudding user response:

In addition to the iterative solution of @candied_orange answer, I'd like to contribute offering a stream implementation. Just stream the elements, filter for the ones that are equal to zero and finally count the number of elements in the stream.

long numZeros = Arrays.stream(arr).filter(i -> i == 0).count();
System.out.println("Num of zeros: "   numZeros);

CodePudding user response:

Declare arrays for zero & counter similar to even and odd :

int zero[] = new int[NUM_COUNT];
int zIdx=0;

And modify your if / else something like:

if (arr[i] == 0)
  zero[zIdx  ] = arr[i];
else if (arr[i] % 2 == 0)
      even[eIdx  ] = arr[i];
 else
    odd[oIdx  ] = arr[i];
  • Related