Task #2: Arrays and Methods
In this task, you are being asked to write a method that manipulates an array in Java.
Write a method called printPrimes that accepts one integer array as argument and print
all the prime numbers form the array.
You may use the following header for this method:
static void printPrimes(int[] array)
For example, if you pass {2, 4, 31, 12, 7, 47, 63, 41, 67, 55} to this
method, then the method should print 2, 31, 7, 47, 41, 67, as prime numbers.
To help with finding a prime number, the printPrimes() method would call another method:
static boolean isPrime(int number)
that takes an integer as an argument, and returns true if that number is a prime, otherwise,
returns false.
NOTE: Declare and initialize the array without taking input from user.
1. Create a program called ArrayPrintPrimesLab2.java
2. Correctly display appropriate messages.
package com.task;
public class ArrayPrintPrimesLab2 {
public static void main(String[] args) {
int[] array = {2, 5, 8, 13, 15, 28, 36, 37, 41, 49, 58};
printPrimes(array);
}
static void printPrimes(int[] array) {
System.out.println("Prime numbers are:");
for (int i = 0; i < array.length; i++) {
if (isPrime(array[i])) {
System.out.print(array[i] + " ");
}
}
}
static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if ((num % i) == 0) {
return false;
}
}
return true;
}
}
Comments
Leave a comment