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); } }
Java count negative numbers in an array output
The Total Number of Negative Array Items = 7
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); } }
In this count negative array items Java example, we created a separate CountNegativeElement function 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; } }
Java count negative numbers in an array using for loop and functions output
Please Enter the CNT NEG Array size : 11
Enter CNT NEG Array 11 elements : -3 -5 0 -8 -11 8 6 99 -22 -55 4
The Total Number of Negative Items = 6