Write a Java Program to count Negative Array Numbers with an example. Or how to write a Java Program to count and return the negative values or items in a given array.
In this Java count negative array numbers example, we used while loop to iterate count_NegArr array and count negative items (a number less than zero) and prints the same.
package ArrayPrograms;
public class CountNegativeArrayItems {
public static void main(String[] args) {
int i = 0, count = 0;
int[] count_NegArr = {-40, 15, -4, 11, -8, -13, 22, 16, -11, -99, 55, 18, -60};
while(i < count_NegArr.length)
{
if(count_NegArr[i] < 0) {
count++;
}
i++;
}
System.out.println("\nThe Total Number of Negative Array Items = " + count);
}
}
OUTPUT
Java Program to Count Negative Array Numbers using For Loop
package ArrayPrograms;
import java.util.Scanner;
public class CountNegativeArrayItems1 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, count = 0;
int[] count_NegArr = new int[10];
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the CNT NEG Array size : ");
Size = sc.nextInt();
System.out.format("\nEnter CNT NEG Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
count_NegArr[i] = sc.nextInt();
}
for(i = 0; i < Size; i++)
{
if(count_NegArr[i] < 0) {
count++;
}
}
System.out.println("\nThe Total Number of Negative Array Items = " + count);
}
}
OUTPUT
In this count negative array items Java example, we created a separate function CountNegativeElement to count and return negative array items.
package ArrayPrograms;
import java.util.Scanner;
public class CountNegativeArrayItems2 {
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 NEG Array size : ");
Size = sc.nextInt();
int[] count_NegArr = new int[Size];
System.out.format("\nEnter CNT NEG Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
count_NegArr[i] = sc.nextInt();
}
int count = CountNegativeElement(count_NegArr, Size );
System.out.println("\nThe Total Number of Negative Items = " + count);
}
public static int CountNegativeElement(int[] count_NegArr, int size ) {
int i, count = 0;
for(i = 0; i < size; i++)
{
if(count_NegArr[i] < 0) {
count++;
}
}
return count;
}
}
OUTPUT