Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Programming - Single-dimensional Arrays Write a Java program to generate 10

ID: 3814455 • Letter: J

Question

Java Programming - Single-dimensional Arrays

Write a Java program to generate 10 random numbers between 0 and 99, figure out the prime numbers in them, and count the number of prime numbers. The program should implement a method to test if a number is a prime as follows: public class Lab6_2 {public static void main(String[] args) {......} public static boolean isPrime(int n) {......}} The following is a sample run of the program: Ten random numbers are: 71 31 63 53 63 36 6 2 20 32 The prime numbers in the list are: 71 31 53 2 The number of prime numbers: 4

Explanation / Answer

Lab6_2.java

import java.util.Random;


public class Lab6_2 {

public static void main(String[] args)
{
Random rn = new Random();
int size = 10;
int[] numbers = new int[size];
for(int i = 0; i < size; i++)
{
numbers[i] = rn.nextInt(100);
}
  
System.out.print("Ten random numbers are: ");
for(int i = 0; i < size; i++)
{
System.out.print(numbers[i] + " ");
}
System.out.println();
  
int primeCount = 0;
System.out.print("The prime numbers in the list are: ");
for(int i = 0; i < size; i++)
{
if(isPrime(numbers[i]))
{
System.out.print(numbers[i] + " ");
primeCount++;
}
}
System.out.println();
System.out.println("The number of primes: " + primeCount);
}
  
public static boolean isPrime(int n)
{
// number 0 and 1 are not prime
if (n <= 1)
return false;
  
// 2 and 3 are known prime
if (n == 2 || n == 3)
return true;
  
// number is divisible by 2 or 3
if (n%2 == 0 || n%3 == 0)
{
return false;
}
  
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;

return true;
}
}

Sample output

Ten random numbers are: 77 55 4 23 29 14 47 6 15 13
The prime numbers in the list are: 23 29 47 13
The number of primes: 4

Please give positive feedbacck if this solved your question.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote