Home » Java Basics » for loop » Generate Prime Numbers with for loop

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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 isPrimeNumber equal 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 boolean isPrimeNumber is 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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments