Java Program to count negative number in an array

Java Program to count negative number in an array

In this tutorial, we will be learning the writing a java program to count the negative number present in an array. To check the negative number our logic will be, using the if else statement we check if the number is smaller than zero.

  • We will be taking the array size and array elements from users as input.
  • Using the if statement we are just checking array element is smaller than zero or not.
  • If smaller than zero, it means the number is negative so increase the count.
  • We have a counter variable negativeCount , which will be increase for every negative number.

Program 1: Java Program to count negative number in an array

import java.util.*;
class Main{
    public static void main(String ...a){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array: ");
        int n = sc.nextInt();
        int arr[] = new int[n];
        int negativeCount=0;
        System.out.println("Enter " +(n)+ " array elements: ");
        for(int i=0; i<n; i++) {
            arr[i] = sc.nextInt();
        } 
        for(int i=0; i<arr.length;i++){
            if(arr[i]<0){
                negativeCount++;
            }
        }
        System.out.println("Total Negative Number : " + negativeCount );
    }
}

Output

Java Program to count negative number in an array

Program 2 : Find negative numbers count in java array using signum()

In this program, we are using the signnum() function to check whether the number is negative or not.

signnum() function takes a double datatype value as an input and it will return -1.0 for negative numbers.

  • So in our program, we are checking if the return value for signnum() is equal to -1.0.
  • Using the if statement we are checking if the return value of signnum() is equal to -1.0 or not.
  • if the condition is satisfied, we will increase the variable count negativeCount by 1 each time.
import java.util.*;
import java.lang.Math.*;  
class Main{
    public static void main(String ...a){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array: ");
        int n = sc.nextInt();
        Double arr[] = new Double[n];
        int negativeCount=0;
        System.out.println("Enter " +(n)+ " array elements: ");
        for(int i=0; i<n; i++) {
            arr[i] = sc.nextDouble();
        } 
        for(int i=0; i<arr.length;i++){
            if(Math.signum(arr[i]) == -1.0){
                negativeCount++;
            }
        }
        System.out.println("Total Negative Number : " + negativeCount );
    }
}

Output

Find negative numbers count in java array