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:
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.
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); } }
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
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions