Write a program to array elements to print sum of Negative Numbers


This is a Java program that takes an array of integers as input from the user and calculates the sum of all negative elements in the array.

  • The program starts by importing the Scanner class from the java.util package, which is used to read input from the user. It then defines a class called Array_Sum_Negative.
  • The main method of the program begins by creating a new Scanner object and asking the user to enter the limit of the array. The user's input is stored in a variable called "l".
  • An array of integers is then created with a length of "l" and is stored in a variable called "a". A variable called "sum" is also initialized to 0, which will be used to store the sum of all negative elements in the array.
  • The program then enters a for loop that iterates "l" times. Each time through the loop, the program prompts the user to enter the value for the corresponding element of the array "a". The user's input is then stored in the array "a".
  • After the for loop completes, the program enters another for-each loop that iterates over each element in the array "a". If the current element is negative (i.e., less than 0), its value is added to the "sum" variable.
  • Finally, the program prints the sum of all negative elements in the array to the console.

Overall, this program is a simple example of how to use loops and conditionals in Java to perform basic calculations on arrays of integers.

Source Code

import java.util.Scanner;
class Array_Sum_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];
		int sum = 0;
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		for(int p:a)
		{
			if(p<0)
				sum = sum + p;
		}		
		System.out.println("Sum of Negative Array Elements : "+sum);
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :10
Element of a[1] :-23
Element of a[2] :45
Element of a[3] :-10
Element of a[4] :30
Sum of Negative Array Elements : -33

Example Programs