Count how many numbers are negative in an array?
Approach:
- Assume array of integer arr = [5,-9,66,-8,37]
- As we know a negative number is a real number less than zero
- We are going to apply the same logic here , and check the number of negative numbers in the array.
- Expected output is : 2 ,since there are 2 negative numbers among the set of numbers
Implementing in Java
/* Read input from STDIN. Print your output to STDOUT*/
import java.io.*;
import java.util.*;
public class CountNegativeNumbers{
public static void main(String args[] ) throws Exception {
//Write code here
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(); // takes user input
int a[] = new int[n]; // creates array depending on the user input
int count=0; //count variable which is zero initially
for(int i=0;i<n;i++){
a[i]=scan.nextInt();
//stores array element inserted by user intoarray
if(a[i]<0){ //check if array element is a negative number
count ++; //increase count if the element is negative
}
}
System.out.println(count); //prints the count of negative numbers
}
}
Output :
2
Happy coding😊
Hi there ! Im a experienced android developer with 4 years of relevant experience Skills include Android,Core Java ,Oops and Kotlin.
Comments
Post a Comment