Java program to print Prime Numbers!

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!

/**
 *
 * @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,

Java Program to print Prime Numbers
Enter the limit:5
2
3
5

Thanks!

Leave a Comment

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

Scroll to Top