Write a Java Program to count Positive Array Numbers with an example. Or how to write a Java Program to count and return the positive values or items in a given array.
In this Java count positive array numbers example, we used while loop to iterate count_PosArr array and count positive items (number greater than or equal to zero) and prints the same.
package ArrayPrograms;
public class CountPositiveArrayItems0 {
public static void main(String[] args) {
int i = 0, count = 0;
int[] count_PosArr = {-10, 15, -4, 11, -8, 22, 16, -11, 55, 18, -60};
while(i < count_PosArr.length)
{
if(count_PosArr[i] >= 0) {
count++;
}
i++;
}
System.out.println("\nThe Total Number of Positive Items = " + count);
}
}

Java Program to Count Positive Array Numbers using For Loop
package ArrayPrograms;
import java.util.Scanner;
public class CountPositiveArrayItems1 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, count = 0;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the CNT POS Array size : ");
Size = sc.nextInt();
int[] count_PosArr = new int[Size];
System.out.format("\nEnter CNT POS Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
count_PosArr[i] = sc.nextInt();
}
for(i = 0; i < Size; i++)
{
if(count_PosArr[i] >= 0) {
count++;
}
}
System.out.println("\nThe Total Number of Positive Items = " + count);
}
}

In this count positive array items Java example, we created a separate function CountPositiveElement to count and return positive array items.
package ArrayPrograms;
import java.util.Scanner;
public class CountPositiveArrayItems2 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the CNT POS Array size : ");
Size = sc.nextInt();
int[] count_PosArr = new int[Size];
System.out.format("\nEnter CNT POS Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
count_PosArr[i] = sc.nextInt();
}
int count = CountPositiveElement(count_PosArr, Size );
System.out.println("\nThe Total Number of Positive Items = " + count);
}
public static int CountPositiveElement(int[] count_PosArr, int size ) {
int i, count = 0;
for(i = 0; i < size; i++)
{
if(count_PosArr[i] >= 0) {
count++;
}
}
return count;
}
}
