write a program in Java to store 20 numbers in a single dimensional array .....display the numbers which are prime...
Answers
Write a program in Java to store 20 numbers in a single dimensional array .....display the numbers which are prime...
Explanation:
Java program to print prime numbers from an array
import java.util.Scanner;
public class Main{
public static void main (String[] args){
int[] array = new int [25];
Scanner in = new Scanner (System.in);
System.out.println("Enter the elements of the array: ");
for(int i=0; i<20; i++)
{
array[i] = in.nextInt();
}
for(int i=0; i<array.length; i++){
boolean isPrime = true;
for (int j=2; j<i; j++){
if(i%j==0){
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(i + " are the prime numbers in the array ");
}
}
}
Output
Enter the elements of the array:
1 2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0 are the prime numbers in the array
1 are the prime numbers in the array
2 are the prime numbers in the array
3 are the prime numbers in the array
5 are the prime numbers in the array
7 are the prime numbers in the array
11 are the prime numbers in the array
13 are the prime numbers in the array
17 are the prime numbers in the array
19 are the prime numbers in the array
23 are the prime numbers in the array
Following are the program in the java language is given below.
Explanation:
import java.util.Scanner; // import package
public class Main // main class
{
public static void main(String[] args) // main method
{
int size=20; // variable declaration
int a[]=new int[size]; // Declared single dimensional array
Scanner scan = new Scanner(System.in); // creating the instance scanner
for (int i=0;i<size;i++) // iterating loop
{
a[i]=scan.nextInt(); // Read array value
}
System.out.print("\nThe prime number are: ");
for (int i=0;i<size;i++) // iterating loop
{
boolean flag = false; // variable declaration and assign
for(int j = 2; j <= a[i]/2;j++) // iterating loop
{
if(a[i] % j == 0) // check condition
{
flag = true;
break;
}
}
if (!flag)
System.out.print(a[i] +","); // display the prime number
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
The prime number are:1,2,3,5,7,11,13,17,19,
Following are the description of program
- Declared the array "a " of type int.
- Declared the variable "size" of type int and assign 20 to them
- Creating the instance of scanner class i.e "scan" for taking the input into the loop
- After that Read the value of array "a" by using the scanner class .
- After that loop will iterated and assign the boolean true or false according to the logic of program .
- If boolean value is true then that number is not prime and it breaks the loop.
- If the flag value will false then it prints the prime number .
Learn More :
- brainly.in/question/1087176