-7
Input:20
Output:0 is not a Prime
       1 is not a prime
       2 is a prime 
       3 is a prime 
       4 is not a prime 
       5 is a prime
       20 is not a prime(upto number 20)

My Class

public class Prime{
    public static void main(String[] args){
        int number=20;
        int p;
        for(int i=2;i<number;i++){
            p=0;
            for(int j=2;j<i;j++){
                if(i%j==0){
                    p=1;
                }
            }
            if(p==0){
                System.out.println(i+" "+"Is Prime");
            }
        }
    }
}

In the above program I printed the prime numbers,How to print both prime and non prime numbers in it?Thanks in advance! check it from 0 is not a Prime, 1 is not a prime, 2 is a prime, 3 is a prime, 4 is not a prime, 5 is a prime, 7 is a prime, 8 is not a prime ,continues upto n given

SDekov
  • 8,531
  • 1
  • 17
  • 43
AngMic
  • 1
  • 2

1 Answers1

0

Add an else block to the if statement that can print non-prime numbers.

if(p==0){
    System.out.println(i+" "+"Is Prime");
}
else {
    System.out.println(i+" "+"Is not Prime");
}

Update:

Also modify your for loop statement like so:

System.out.println("0 is not Prime");
System.out.println("1 is not Prime");
for(int i=2;i<=number;i++){

This will iterate from 0 to 20.

anacron
  • 6,093
  • 2
  • 24
  • 31
  • Yup! but if i added these lines it gives the output from 2 to 19 only.I have to start with the 0 to 20.0 is not a prime 1 is not a prime. 2 is a prime.Likewise upto 20 is not a prime. – AngMic Dec 20 '16 at 18:35
  • 0 and 1 is not a Prime .If am declaring the for loop as like for(int i=0;i<=number;i++).It returns the output 0 is a prime 1 is a prime. – AngMic Dec 21 '16 at 12:02
  • By definition, 0 and 1 are not prime numbers and are generally not considered while calculation. You can choose to print them separately before starting your loop.. – anacron Dec 21 '16 at 12:06