Write a java program to input 10 numbers into an arrey and replace all prime numbers in it by 0 and print the notified array.
Answers
- Write a java program to input 10 numbers in an array and replace all the prime numbers in it by 0 and print the modified array.
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);
}
public static void main(String s[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 elements in array. ");
int a[]=new int[10];
for(int i=0;i<10;i++)
{
System.out.print("["+i+"]=");
a[i]=sc.nextInt();
}
for(int i=0;i<10;i++)
{
if(isPrime(a[i]))
a[i]=0;
}
System.out.print("The new array is: ");
for(int i=0;i<10;i++)
System.out.print(a[i]+" ");
}
}
import java.util.Arrays;
import java.util.Scanner;
public class PrimeArray {
static boolean isPrime(int number) {
for (int i = 2; i < number; i++)
if (number % i = = 0)
return false;
return true;
}
public static void main(String[ ] args) {
int[ ] array = new int[10];
System.out.println("Enter 10 numbers - ");
for (int i = 0; i < 10; i++)
array[i] = new Scanner(System.in).nextInt( );
System.out.println("Array Before - " + Arrays.toString(array));
for (int i = 0; i < 10; i++)
if (isPrime(array[i]))
array[i] = 0;
System.out.println("Array After - " + Arrays.toString(array));
}
}