Prime Numbers In Array

Prime Numbers In Array


Write a program to find the number of prime elements in an array.

// Write a program to find the number of prime elements in an array.

import java.util.*;

class PrimesInArray{
    public static void main(String args[])throws InputMismatchException{

        int i, ctr, n;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number of terms: ");
        n = sc.nextInt();

        //create array of 'n' elements
        int a[] = new int[n];

        System.out.println("Enter "+n+ " integers");

        for(i=0;i<n;i++){
            a[i]=sc.nextInt();
        }

        ctr = 0; //counter for prime elments
        for(i=0;i<n;i++)
        {

            if(isPrime(a[i]))
                ctr++;
        }

        System.out.println("Number of prime elements in the array: "+ctr);

    }//end of main

    //Return true if number is prime else return false
    private static boolean isPrime(int p){

        for(int i = 2; i <= p/2; i++){
            if(p%i == 0)
                return false;
        }
        return true;
    }
}//end of class

Have something to say? Log in to comment on this post.

0 comments