Write a program to array elements to print sum of Even Numbers
This is a Java program that prompts the user to enter an array of integers, and then calculates the sum of all even elements in the array. Here is a step-by-step explanation of how the program works:
- The program starts by importing the java.util.Scanner class, which is used to read user input from the console.
- The Array_Sum_EvenNum class is defined, which contains the main method that will be executed when the program runs.
- Inside the main method, a Scanner object is created to read user input.
- The user is prompted to enter the array limit, which is the maximum number of elements that the array can hold. The user input is stored in the l variable.
- An integer array a of size l is created.
- A for loop is used to prompt the user to enter each element of the array. The loop iterates l times, and for each iteration, the user is prompted to enter an integer value, which is then stored in the corresponding index of the array a.
- Another for loop is used to iterate through all the elements of the array a. For each element e, the loop checks if e is even by using the modulus operator (%) to determine if e is divisible by 2. If e is even, its value is added to the sum variable.
- Finally, the program prints out the sum of all even elements in the array.
Source Code
import java.util.Scanner;
class Array_Sum_EvenNum
{
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 e:a)
{
if(e%2==0)
sum = sum + e;
}
System.out.println("Sum of Even Array Elements : "+sum);
}
}
Output
Enter the Array Limit :5
Element of a[0] :56
Element of a[1] :78
Element of a[2] :45
Element of a[3] :79
Element of a[4] :34
Sum of Even Array Elements : 168