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


This Java program takes input from the user for the size of the array and the elements of the array. It then calculates the sum of all the positive 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.
  • An integer variable "sum" is initialized to zero.
  • 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 add all positive elements to the variable "sum".
  • The final sum of positive elements is printed.

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

Source Code

import java.util.Scanner;
class Array_Sum_Positive
{
	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 Positive Array Elements : "+sum);
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :1
Element of a[1] :-2
Element of a[2] :3
Element of a[3] :3
Element of a[4] :-4
Sum of Positive Array Elements : 7

Example Programs