Sum Of Prime Elements Of An Array

Sum Of Prime Elements Of An Array


Write a program to display the sum of prime elements in a n x n matrix.

import java.io.*; class SumOfPrimes { public static void main(String ar[])throws Exception { BufferedReader ob=new BufferedReader( new InputStreamReader(System.in)); int i,j,k,nof,sum=0; int a[][]=new int[3][3]; System.out.println("Enter "+(3*3)+" elements "); for(i=0;i< 3;i++) { for(j=0;j< 3;j++) { a[i][j]=Integer.parseInt(ob.readLine()); } } for(i=0;i< 3;i++) { for(j=0;j< 3;j++) { nof=0; for(k=1;k<=a[i][j];k++) { if(a[i][j]%k==0) nof++; } if(nof==2) sum=sum+a[i][j]; } } System.out.println("\nSum of prime elements = "+ sum); } }

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

0 comments