Programming Examples

Java program to count and print the prime Elements in array


Write a java program to print and count the prime elements present in array.

Solution:

import java.util.*;
class PrimeElements
{
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the size of Array : ");
        int size=sc.nextInt();
        int num[]=new int[size];
        System.out.println("Enter "+size+" Elements for Array :");
        for(int i=0;i<size;i++)
        {
            num[i]=sc.nextInt();
        }
        boolean flag; 
        int count=0;
        for(int i=0;i<size;i++)
        {
            flag=true;
            for(int b=2;b<=num[i]/2;b++)
            {
                if(num[i]%b==0)
                {
                    flag=false;
                    break;
                }
            }
            if(flag==true && num[i]!=1)
            {
                count++;
                System.out.print(num[i]+" ");
            }
        }
        System.out.println("\nTotal no of Prime Elements in array are : "+count);
       
    }
}
Output

Enter the size of Array : 

5

Enter 5 Elements for Array :

3

4

5

10

11

3 5 11 Total no of Prime Elements in array are : 3

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz