Write a program to array elements print all Negative number


This Java program takes input from the user for the size of the array and the elements of the array. It then prints all the negative elements of the array. Here is a brief explanation of the program:

  • First, the program imports the Scanner class from the java.util package to take input from the user.
  • The main method is declared and the Scanner object is created.
  • The user is prompted to enter the size of the array, which is stored in the integer variable "l".
  • An integer array "a" of size "l" is created.
  • A for loop is used to take input from the user for each element of the array "a".
  • The input values are stored in the array "a".
  • Another for-each loop is used to iterate through the array "a" and print all negative elements.

Note that this program only prints the negative elements of the array. If you want to print both positive and negative elements, you can modify the program by removing the if condition inside the for-each loop.

Source Code

import java.util.Scanner;
class ArrayNum_Negative
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		System.out.println("\nNegative Array Elements...\n");
		for(int n:a)
		{
			if(n<0)
				System.out.println(n);
		}
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :-45
Element of a[1] :32
Element of a[2] :-7
Element of a[3] :3
Element of a[4] :-6

Negative Array Elements...

-45
-7
-6

Example Programs