C++ Program to check whether given number is prime or not.

// C++ Program to check whether given number is prime or not.

#include <iostream>
using namespace std;
int main()
    {
        int n, i, flag = 0;
        cout<<"Enter a positive integer: ";
        cin>>n;
        for(i = 2; i <= n/2; ++i)
        {
            // Condition for Nonprime number
            if(n%i == 0)
            {
                flag = 1;
                break;
            }
        }
        if (n == 1) 
        {
          cout<<"1 is neither a prime nor a composite number.";
        }
        else 
        {
            if (flag == 0)
              cout<<n<<" is a prime number.";
            else
              cout<<n<<" is not a prime number.";
        }
        return 0;
    }

Output :
Enter a positive integer: 17
17 is a prime number.


Description :

A prime number can be divided, without a remainder, only by itself and by 1. For example, 17 can be divided only by 17 and by 1.


Leave a comment