Implement a nested for loop to jind the prime number up to n numbers. print all the prime numbers up to N, we start one loop from 2 to N and then inside the loop we check current number or “num” is prime or not. To check if it is prime or not we again need one nested loop. It is not an efficient way to check prime number but it is simpler to understand the basic of looping in Java
class printPrime
{
static void printPrime(int n)
{
for(int i=2;i<=n;i++)
{
int count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0) //if the number is divisible by j
count++;
}
if(count==2) //checking if the number is prime
System.out.print(i+" ");
}
}
public static void main(String[] args)
{
int n = 10;
printPrime(n);
}
}
for any doubt just leave a comment else please press the like button
Get Answers For Free
Most questions answered within 1 hours.