+ 1

# Check prime numbers from 1 to 100

public class Program { public static void main(String[] args) { for(int i=1;i<=100;i++) { boolean flag = true; for(int j=2;j<=i-1;j++) { if(i%j==0) { flag = false; break; } } if(flag == true) { System.out.print(i); System.out.print("\t"); } } } } //Please someone explain me at least one iteration

6 Answers

+ 1

flag represents the truth of "i is prime" when it gets to the "if(flag == true)" line. A much clearer name would be iIsPrime.
i%j will be true only if i is divisible by j. A prime number is a number i such that isn't divisible by any number j from 2 up to and including that number minus 1. The for(int j=2;...) loop updates flag to false only when i is proven to not be prime.

+ 6

// if i is prime, print i.
if(flag == true)
{
System.out.print(i);
System.out.print("\t");
}

+ 1

The opposite of what you said.
// if i is prime, print i.
if(flag == true)
{
System.out.print(i);
System.out.print("\t");
}

+ 1

Ex: 5
initially flag =true.
Inner if i%j==0 never true.. (for 2,3,4). So flag won't change..
Outer if flag ==ture is ture, then prints 5.
Ex: 4
In inner if, 4%2==0 true, flag set to false. Breaks loop.
It will not print by outer if.

0

if condition telling that it is not a prime number right ?

0

Thank you so much for the help !!