Home
Refer
Jobs
Alumni
Resume
Notifications

Write a program in Java that finds all the prime numbers between 0 and N, where N is an integer input provided by the user.

🚀 Best Answers Get Featured in our LinkedIn Community based on Your Consent, To Increase Your Chances of Getting Interviewed. 🚀

Sure, below is a solution in Java that finds all the prime numbers between 0 and N, where N is an integer input provided by the user:
```javaimport java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:
");
int n = input.nextInt();
System.out.print("Prime numbers between 0 and " + n + " are:
");
for(int i = 2;
i <= n;
i++) {
boolean isPrime = true;
for(int j = 2;
j < i;
j++) {
if(i % j == 0) {
isPrime = false;
break;
}
}
if(isPrime) System.out.print(i + " ");
}
}
}

```Explanation:- First, we import the `Scanner` class to get the user input.- Then, we prompt the user to enter a number and store it in variable `n`.- We set up a `for` loop to iterate from 2 to `n`.- For each iteration of the loop, we initialize the boolean variable `isPrime` to `true`.- We set up another nested `for` loop to check if the current number `i` is prime. We start with `j = 2` and increment `j` until `j` reaches `i-1`. If `i` is divisible by `j`, then it is not prime. In this case, we set `isPrime` to `false` and break out of the nested loop.- After the nested loop ends, we check the value of `isPrime`. If it is still `true`, that means `i` is prime and we print it out to the console.Citations:- To understand how to use the `Scanner` class to get user input in Java, [click here](https://www.w3schools.com/java/java_user_input.asp).- To learn more about prime numbers and how to check for them, [click here](https://www.geeksforgeeks.org/java-program-to-check-if-a-number-is-prime-or-not/).I hope this solution helps you prepare for your interview! Best of luck.

© 2024 Referral Solutions, Inc. Incorporated. All rights reserved.