While Loop – Print Prime Numbers in Java

How to print prime number using while loop in java?  Before jump to this question’s answer, you need to know what is a prime number? A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. For example: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 and more…

While Loop

It is a looping construct control statement that executes the block of code while the condition is true. Loop will never get executed if the condition is false.  In another word, while Loop is used when the number of iteration is not fixed. It performs a part of the program many times.

while<loop condition>

In java language, ‘while’ is one of the most used after ‘for loop’. It’s a control flow statement that allows code to be executed repeatedly based on condition.


[ Output: 1 2 3 4 5 6 7 8 9 10 ]

Example 1: Print Prime Numbers from 1 to N using While Loop

So, how to print prime numbers in while loop? Here is the best example:

Prime number using while loop

Here’s the code for the prime number :

[ Output : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 ]

Example 2: Check Prime Numbers using a while loop

You can check prime number using a while loop in java. Here is an example:

Check Prime Number using a while loop

Here’s the code to check prime numbers :

Related posts:

Loops in Java [ For, While & Do While ] with Examples

Scanner Class in Java – java.util.package

Switch, Break, Continue & Comment Statements in Java

String to int in Java – Convert int to String

Collections in Java – with Examples For Beginners

Inner Classes in Java With Examples

String in Java – Everything You Need to Know

Object Class methods in Java | Methods of the Object class

Leave a Reply

Your email address will not be published. Required fields are marked *