Java Program to Display Prime Numbers from 1 to 100
- January 03, 2021
- by
Java Program to Display Prime Numbers from 1 to 100
In this Java Program, prime numbers from 1 to 100 are displayed to the user.
A prime number is a natural number greater than 1 that is not a product of two small natural numbers.
E.g. 2, 3, 5 etc are prime numbers.
Step 1 : Initialize i to zero
Step 2 : Initialize num to zero
Step 3 : Create an empty string named as primeNnumbers
Step 4 : Apply for loop where num is equal to i, num is greater than equal to 1 and decrement num
Step 5 : Apply if statement inside for loop where i mod num is equal equal to zero
Step 6 : Increment counter by one and store it in counter variable
Step 7 : Close the for loop
Step 8 : Apply if statement where counter is equal equal to 2
Step 9 : Append the prime number to the string
Step 10 : Print the output by using System.out.println method
Program :
public 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:
2357111317192329313741434753596167717379838997
For execution of the same do visit my YouTube Channel :


0 comments:
Post a Comment