for loop
Generate Prime Numbers with for loop
With this example we are going to demonstrate how to generate prime numbers with a simple for loop. A prime number is a number that has no positive divisors other than 1 and itself. In short, to generate a prime number using a for loop you should:
- Create a for statement with an int i variable from 1 to a max int number, and step equal to 1.
- For each one of the numbers in the loop create a boolean
isPrimeNumberequal to true and create another loop where the number is divided to other numbers from 2 up to the number, and if the result is zero, then the booleanisPrimeNumberis set to false.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.basics;
public class GeneratePrimeNumbersWithForLoop {
public static void main(String[] args) {
int max = 100;
System.out.println("Generate Prime numbers between 1 and " + max);
// loop through the numbers one by one
for (int i = 1; i<max; i++) {
boolean isPrimeNumber = true;
// check to see if the number is prime
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrimeNumber = false;
break; // exit the inner for loop
}
}
// print the number if prime
if (isPrimeNumber) {
System.out.print(i + " ");
}
}
}
}
Output:
Prime numbers between 1 and 100
1 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
This was an example of how to generate prime numbers with a simple for loop in Java.
