Java program to display prime numbers between intervals using function
Here's a Java program that displays prime numbers between intervals using a function:
import java.util.Scanner; public class PrimeNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the lower bound of the interval: "); int lowerBound = scanner.nextInt(); System.out.print("Enter the upper bound of the interval: "); int upperBound = scanner.nextInt(); System.out.println("Prime numbers between " + lowerBound + " and " + upperBound + " are: "); for (int i = lowerBound; i <= upperBound; i++) { if (isPrime(i)) { System.out.print(i + " "); } } } public static boolean isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } }Sourcww:ew.theitroad.com
Explanation:
The program first creates a Scanner
object to read user input from the console. It then prompts the user to enter the lower and upper bounds of the interval by printing the messages "Enter the lower bound of the interval: " and "Enter the upper bound of the interval: " to the console.
The nextInt
method of the Scanner
object is called to read the next integer values entered by the user and store them in the lowerBound
and upperBound
variables, respectively.
The program then prints the message "Prime numbers between lowerBound
and upperBound
are: " to the console.
The program then uses a for
loop to iterate over all integers between lowerBound
and upperBound
. For each integer i
, the isPrime
function is called to check if i
is a prime number. If it is, the value of i
is printed to the console.
The isPrime
function takes an integer n
as its argument and returns a boolean value indicating whether n
is a prime number or not. The function first checks if n
is less than or equal to 1, in which case it returns false
. If n
is greater than 1, the function uses a for
loop to check if n
is divisible by any integer between 2 and the square root of n
. If n
is divisible by any of these integers, the function returns false
. Otherwise, the function returns true
.
Note that this program assumes that the user enters valid integer values for the lower and upper bounds of the interval. If the user enters non-integer values, the program will throw an exception. You could add input validation code to handle this case.