Java Tutorials
Java ArrayList: How to Use, ArrayList Methods & Examples
What is ArrayList in Java? ArrayList in Java is a data structure that can be stretched to...
A Prime Number is a number that is only divisible by one or itself. It is a natural number greater than one that is not a product of two smaller natural numbers. For example, 11 is only divisible by one or itself. Other Prime numbers 2, 3, 5, 7, 11, 13, 17, etc.
Note: 0 and 1 are not prime numbers. 2 is the only even prime number.
Below is the Java program to print prime numbers from 1 to 100:
Program Logic:
CheckPrime to determine whether a number is prime number in Java or not.numberToCheck is entirely divisible by another number, we return false, and loop is broken.numberToCheck is prime, we return true.TRUE and add to primeNumbersFound String public class primeNumbersFoundber {
public static void main(String[] args) {
int i;
int num = 0;
int maxCheck = 100; // maxCheck limit till which you want to find prime numbers
boolean isPrime = true;
//Empty String
String primeNumbersFound = "";
//Start loop 2 to maxCheck
for (i = 2; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
}
}
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
// Print prime numbers from 1 to maxCheck
System.out.println(primeNumbersFound);
}
public static boolean CheckPrime(int numberToCheck) {
int remainder;
for (int i = 2; i <= numberToCheck / 2; i++) {
remainder = numberToCheck % i;
//if remainder is 0 than numberToCheckber is not prime and break loop. Else continue loop
if (remainder == 0) {
return false;
}
}
return true;
}
}The output of the prime number between 1 to 100 in Java program will be:
Prime numbers from 1 to 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Check our program to Find Prime Numbers from Any Input Number
What is ArrayList in Java? ArrayList in Java is a data structure that can be stretched to...
What is JSON? JSON is an abbreviation for Javascript Object Notation, which is a form of data that...
What is JasperReports for Java? JasperReports is an open-source reporting tool for Java that is...
What Is An Array Of Objects? JAVA ARRAY OF OBJECT , as defined by its name, stores an array of...
Java Tutorial Summary This Java tutorial for beginners is taught in a practical GOAL-oriented way....
Download PDF We have compiled the most frequently asked Java Interview Questions and Answers that...