BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java program to display prime numbers from 1 to 100 and 1 to n

Last Updated: September 10, 2022 by Chaitanya Singh | Filed Under: Java Examples

The number which is only divisible by itself and 1 is known as prime number. For example 2, 3, 5, 7…are prime numbers. Here we will see two programs: 1) First program will print the prime numbers between 1 and 100 2) Second program takes the value of n (entered by user) and prints the prime numbers between 1 and n. If you are looking for a program that checks whether the entered number is prime or not then see: Java Program to check prime number.

Program to display the prime numbers from 1 to 100

It will display the prime numbers between 1 and 100.

class PrimeNumbers
{
   public static void main (String[] args)
   {		
       int i =0;
       int num =0;
       //Empty String
       String  primeNumbers = "";

       for (i = 1; i <= 100; i++)         
       { 		  	  
          int counter=0; 	  
          for(num =i; num>=1; num--)
	  {
             if(i%num==0)
	     {
 		counter = counter + 1;
	     }
	  }
	  if (counter ==2)
	  {
	     //Appended the Prime number to the String
	     primeNumbers = primeNumbers + i + " ";
	  }	
       }	
       System.out.println("Prime numbers from 1 to 100 are :");
       System.out.println(primeNumbers);
   }
}

Output:

Prime numbers from 1 to 100 are :
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

Program to display prime numbers from 1 to n

It will display all the prime numbers between 1 and n (n is the number, entered by user).

import java.util.Scanner;
class PrimeNumbers2
{
   public static void main (String[] args)
   {		
      Scanner scanner = new Scanner(System.in);
      int i =0;
      int num =0;
      //Empty String
      String  primeNumbers = "";
      System.out.println("Enter the value of n:");
      int n = scanner.nextInt();
      scanner.close();
      for (i = 1; i <= n; i++)  	   
      { 		 		  
         int counter=0; 		  
         for(num =i; num>=1; num--)
         {
	    if(i%num==0)
	    {
		counter = counter + 1;
	    }
	 }
	 if (counter ==2)
	 {
	    //Appended the Prime number to the String
	    primeNumbers = primeNumbers + i + " ";
	 }	
      }	
      System.out.println("Prime numbers from 1 to n are :");
      System.out.println(primeNumbers);
   }
}

Output:

Enter the value of n:
150
Prime numbers from 1 to n are :
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 101 103 107 109 113 127 131 137 139 149

Top Related Articles:

  1. Java Program to Calculate average using Array
  2. Java program to check prime number
  3. java program to check palindrome string using recursion
  4. Autobiographical Number in Java with example
  5. Sphenic Number in Java – Check and Print all numbers in a range

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Saleema says

    June 25, 2014 at 6:41 AM

    can you explain in details of the 1st program. I can’t seem to quite follow your logic. Thanks in advance.

    Reply
    • Subba Reddy Mettu says

      July 10, 2015 at 9:55 PM

      The person who wrote the logic has written a very good code, I am not expert in java and this would be my first explanation hope you will like it.
      int n = scanner.nextInt() – It takes the input from the user to find the prime numbers in a particular range say 100.
      for (i = 1; i =1; num–) – for (1=i; 1>=1; 1–) 1– is 0 next step is if(i%num==0) – 1%1 ==0 yes counter = 0 + 1 which is 1 now num is 0 so num>=1 which is 0>=1 false come out of loop.
      so, the counter is just 1, if the counter is exactly equal to two that means if the numbers have exactly two factors which is one and itself the the number is updated to prime number and is printed.
      lets see true condition: say number is 5
      for(num =i; num>=1; num–) – for (5=i; 5>=1; 5–) 5– is 4 next step is if(i%num==0) – 5%5 ==0 yes counter = 0 + 1 which is 1 now num is 4 so num>=1 which is 4>=1 true execute the loop again.
      for(num=i;num>=1;num–) – for(4=i; 4>=1; 4–) 4– i%num for 5%4 is 1 and 5%3 is 2 for 5%2 its 1 and for 5%1 its zero, so increase counter by 1 so the counter is exactly equal to 2 so 5 is a prime number and it printed at end.

      Reply
      • gangadhar says

        August 23, 2016 at 10:42 AM

        will you explain this
        primeNumbers = primeNumbers + i + ” “;

        Reply
        • Manjunath says

          June 2, 2017 at 3:29 AM

          look at this declaration

          String primeNumbers = “”;

          primeNumbers is declared as of type String so,

          whenever new prime number is found its been appended to the same string with white space in between. (would have used array rather)

          primeNumbers = primeNumbers + i + ” “;

          Reply
    • A.S Sahshransu says

      October 27, 2015 at 6:11 AM

      The Best Ever Writer Of the Program Is Thanks receiver From Me
      I am grateful to you
      I was able to do my Projects Well
      Thank You Very Much Beginner’s Book
      I Shall Visit Again For Knowledge
      The Great site Of Knowledge I have Ever seen

      Reply
  2. sivaiah says

    December 29, 2014 at 1:05 PM

    Very nice logic…Thanks

    Reply
    • Chaitanya Singh says

      December 30, 2014 at 2:37 PM

      Glad to know that you liked it.

      Reply
      • Anonymous says

        May 15, 2016 at 1:07 PM

        Hey,I just went through your code seems very good,I need your help with some java codes please?

        Reply
  3. sai.g says

    June 25, 2015 at 4:53 AM

    Good logic very nice

    Reply
  4. Akansh says

    August 5, 2015 at 2:58 AM

    I was stuck for 2 day thinking about the logic.Thanks I got it here good and simple.

    Reply
    • Manav says

      October 27, 2015 at 6:26 PM

      Can you explain please?

      Reply
    • venkat says

      December 13, 2015 at 2:42 PM

      i need too easy one

      Reply
  5. SaitamaJBP says

    November 8, 2015 at 6:47 AM

    class Number3
    {
    public static void main (String[] args)
    {
    for(int x = 1 ; x 1)
    System.out.print(x+” “);
    }
    }
    }
    //this Program Will Show All The prime numbers from 1-100
    Sorry my logic is not too deep but i display it right ?
    Can i get some opinion ?

    Reply
  6. Qamran Rajput says

    February 13, 2016 at 4:31 AM

    Very Nice Simple Short and easy solution.
    Thankyou

    Reply
  7. shashank siriga says

    June 3, 2016 at 8:23 PM

    hey we can use stringbuffer instead of string which may reduce the space in the sotrage for the programm

    Reply
  8. Pele says

    June 9, 2016 at 8:41 AM

    How do you make a space between Prime Number when you print out?
    can you tell me?

    Reply
    • Ankit Bhardwaj says

      November 24, 2016 at 2:54 PM

      primeNumbers = primeNumbers + i + ” “;

      if you see this you would see a space between double quotes. This basically add the space . if you increase it the space between the number will increase .

      Reply
  9. Shubham kankal says

    August 5, 2016 at 5:26 PM

    we can not display directly prime numbers……i mean empty string in mandatory…..???

    Reply
    • Ankit Bhardwaj says

      November 24, 2016 at 2:58 PM

      yes you can that but this empty string is just used to add space between two numbers.

      Reply
  10. Will Rodriguez says

    October 28, 2016 at 3:44 AM

    For those of you wanting an explanation on whats going on in here, here it goes!

    He is reading a number from standard input: (Console)

    Then you are looping from 1 up to the n provided, i.e n=5, 1,2,3,4,5.
    Then you’re trying to only append the primes to the string.
    Recall a prime number, are those numbers that can only be divided by 1 and itself.
    He then starts looping through the current number, until he reaches 1. Counting the number of times the current number was evenly divided.
    for example, current number is 5, then he loops going back from 5 until 1.
    5,4,3,2,1. During each iteration, he then checks to see if the current number, in this example 5, is evenly divisible by any other number (i%number ==0)
    5%5==0, true, increment counter
    5%4==0, false,
    5%3==0, false,
    5%2==0, false
    5%1==0, true, increment counter

    At this point, only 2 numbers evenly divided 5, therefore, 5 is prime!
    We now append the current number to our string.

    Hope this helped!!

    Oh and for that person that asked if it’s better to use a stringbuffer, well yes! Strings are immutable, therefore, every time you are appending a value to it, you are creating a new string object!

    Reply
  11. Jospin Okamba says

    January 21, 2017 at 1:07 AM

    what i want my output start from let say 3 instead of 2, what change should should i make on the second project or code u wrote

    Reply
  12. ashish maheshwari says

    September 2, 2017 at 6:31 PM

    very well explained,i m stuck in one part,say i am using scanner to take entry from user,now if i want this scanner input entry from user again n again without re running the program how can i do.
    please suggest
    thanks

    Reply
    • Chaitanya Singh says

      September 3, 2017 at 4:04 AM

      You can place the scanner in a while loop and inside loop along with scanner, ask user whether he/she wants to continue(like Y/N, Y for yes and N for no), run the loop until that new variable is equal to N.

      Reply

Leave a Reply Cancel reply

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

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap