Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

my output is printing multiple times

+6 votes
asked Jan 25 by Harshini ganji (180 points)
class Prime
{
  public static void main (String[]args)
  {
    int n = 17;
     if (n <= 1)
      {
  System.out.println (" not a prime number");
      }

    for (int i = 2; i <= n / 2; i++)
      {
  if (n % i == 0)
    {
      System.out.println ("not a prime number");
    }
  else
    {
      System.out.println ("prime number");
    }
      }
  }

}

2 Answers

+2 votes
answered Jan 27 by Sagar Bangari (180 points)
class Prime
{
    public static void main (String[]args)
    {
         int n = 16;
         if (n <= 1){
             System.out.println (" not a prime number");
             System.exit(0);  // If n is less than or equal to 1 then print not a prime number and exit the program

             // System.exit(0) function terminates the program
         }

        for (int i = 2; i <= n / 2; i++){
      
            if (n % i == 0)
             {
                System.out.println ("not a prime number");
                System.exit(0);// If n is divisible by i then print not a prime number and exit the program

             }
        }

        // After completing the loop if n is prime number then if condition in for loop will never run therefore we print

        n is prime number
        System.out.println("prime number");
  }

}
commented Jan 29 by Poorvith (120 points)
this is because you have typed the input
 it so many times are you alert on what are you doing
+1 vote
answered Jan 27 by Peter Minarik (82,920 points)

This is, because in your for loop you print something every single time you check n % i.

Instead, you should quit (return) when you find that n % i == 0 and only print that the number is a prime after your for loop is finished (meaning you didn't find any divider). 

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...