Write a program to array elements print all Even number


This Java program takes user input for the size of an array, then prompts the user to enter the elements of the array. It then finds and prints all the even elements of the array. Here is how the program works:

  • First, it imports the Scanner class from the java.util package to allow user input.
  • It declares a class called Array_EvenNum.
  • It declares a main method that takes no arguments and has a return type of void.
  • Within the main method, it creates a new Scanner object called input to take user input.
  • It prompts the user to enter the limit of the array and reads the input as an integer.
  • It creates a new array of integers called a with the size of the limit input by the user.
  • It then prompts the user to enter the elements of the array, and reads each element as an integer and stores it in the corresponding index of the array.
  • It then prints a message to indicate that it will display only the even elements of the array.
  • It then iterates over the elements of the array using a for loop and prints the value of each element if it is even (i.e. if the remainder of the division by 2 is 0).
  • Finally, the program ends.

Note that this program assumes that the user will only input integers, and it does not handle any potential exceptions or errors. Also, it's a good practice to close the Scanner object after use to avoid memory leaks. However, it's not required in this program as the Scanner object is only used within the main method and will be automatically garbage collected after the program ends.

Source Code

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

Output

Enter the Array Limit :5
Element of a[0] :23
Element of a[1] :45
Element of a[2] :89
Element of a[3] :34
Element of a[4] :12

Even Array Elements...

34
12

Example Programs