Wap in Java to store 20 different numbers in a SDA. Pass this array to a function and display only prime numbers along with their sum.
Answers
import java.util.Scanner;
public class Prime {
static boolean isPrime(int number) {
for (int i = 2; i < number; i++)
if (number % i = = 0)
return false;
return true;
}
static void printPrimeAndSum(int[ ] array) {
System.out.println("\nPrime numbers - ");
int primeSum = 0;
for (int number : array)
if (isPrime(number)) {
primeSum += number;
System.out.print(number + " ");
}
System.out.println("\nPrime numbers sum - " + primeSum);
}
public static void main(String[ ] args) {
System.out.println("Enter 20 Integers - ");
int[ ] array = new int[20];
for (int i = 0; i < 20; i++)
array[i] = new Scanner(System.in).nextInt( );
printPrimeAndSum(array);
}
}
- Write a program in Java to store 20 different numbers in SDA. Pass this array to a function and display only prime numbers along with sum.
import java.util.*;
class Array
{
static boolean isPrime(int n)
{
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
return (c==2);
}
static void Print(int a[])
{
System.out.println("The prime numbers are...");
int s=0;
for(int i:a)
{
if(isPrime(i))
{
s+=i;
System.out.print(i+" ");
}
}
System.out.println("Sum of all the prime numbers in the array is: "+s);
}
public static void main(String s[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements. ");
int a[]=new int[20];
for(int i=0;i<20;i++)
{
System.out.print("Enter: ");
a[i]=sc.nextInt();
}
Print(a);
}// end of main()
}// end of class.