Join super friendly code & developer communities
A place for coders and developers to share, learn and grow together.
This is a tutorial for counting positive, negative, even, odd numbers from arrays. The program is given below that takes numbers from users counts the +ve,-ve,even,odd numbers and prints them. The program is extendable. Go enjoy the program. Lets begin…
Program for counting positive, negative, even, odd numbers from array in java.
//import Scanner as we require it.
import java.util.Scanner;
// the name of our class its public
public class ArrayCount {
//void main
public static void main (String[] args)
{
//declare int
int i,x,a[] = new int[10];
//declare int as set them 0
int n=0,p=0,e=0,o=0;
//Declare input as scanner
Scanner input = new Scanner(System.in);
//Take input for arrays
for(i=0;i<5;i++)
{
System.out.println("Enter Number :");
a[i] = input.nextInt();
}
//count
for(i=0;i<5;i++)
{
if(a[i]<0)
n++;
else
p++;
x=a[i]%2;
if(x==0)
e++;
else
o++;
}
//print
System.out.println("Total Even Numbers = "+e);
System.out.println("Total Odd Numbers = "+o);
System.out.println("Total Negative Numbers = "+n);
System.out.println("Total Positive Numbers = "+p);
}
}
Output
Enter Number :
1
Enter Number :
-2
Enter Number :
-3
Enter Number :
4
Enter Number :
5
Total Even Numbers = 2
Total Odd Numbers = 3
Total Negative Numbers = 2
Total Positive Numbers = 3
How does it work
1. You enter the number.
2. The number is saved in respective array.
3. The numbers from arrays are taken and tested if even or odd or +ve or -ve.
4. The respective counters are increase.
5. The counters are printed.
Extending it
The program can be extended by taking counter of prime numbers. Try it. Extend it.
Explanation.
1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Declare input as Scanner.
5. Add a for loop.
6. Add system.out.println() function with the message to enter number.
7. Take the inputs and save it in arrays.
8. Add one more loop to count the different types of numbers.
9. Add system.out.println() function to print the counters.
At the end.
You learnt creating the Java program for Counting positive, negative, even, odd numbers from arrays. So now enjoy the program.
P.S. If you have any questions, click here to join our community and feel free to ask any questions.