Hi friends,
In this post, we are going to discuss how to print a series of Prime numbers using Core Java. This basic Java program will help you to understand the fundamentals of the Java programming.
So basically the entire program is here. Just go through and ask me doubts in the comments section if you have any!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
/** * * @author agur */ import java.util.Scanner; public class Prime { public static void main(String[] args){ //define the integers int i, j, limit, c; Scanner in = new Scanner(System.in); System.out.println("Java Program to print Prime Numbers"); //get the limit from user System.out.print("Enter the limit:"); limit = in.nextInt(); //loop till i equals to $limit for(i=1; i <= limit; i++){ c = 0; for(j=1; j <= i; j++){ // % modules will give the reminder value, so if the reminder is 0 then it is divisible if (i % j == 0) { //increment the value of c c++; } } //if the value of c is 2 then it is a prime number //because a prime number should be exactly divisible by 2 times only (itself and 1) if (c == 2) { System.out.println(i); } } } } |
Example output of the program is below,
1 2 3 4 5 |
Java Program to print Prime Numbers Enter the limit:5 2 3 5 |
Thanks!