Computer Science, asked by gurjargeetansh1, 7 months ago

Java program to display prime numbers between 1 to 100 or 1 to n.​

Answers

Answered by saifizaid44
4

ANSWER: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

Answered by TanishaAeran
1

Answer:

The number which is divisible by 1 and itself

Explanation:

public class Prime

{

public static void main (String args[ ])

{

int a,b;

System.out.println (" The prime numbers between 1 and 100 are :");

for ( a= 1 ; a<=100; a++)

{

int c = 0;

for ( b =1; b<= a; b ++)

{

if ( a%b==0)

c = c+1;

}

if (c==2)

System.out.println(a);

}

}

}

Similar questions