C++ Program to check a Given Number is Prime or Not.

Prime numbers are the positive integers having only two factors, 1 and the integer itself.

// Example
2, 3, 5, 7, 11, 13, 17 ....

How to execute this Program

  • Define Variables “num” & “count” ( Where count=0 )
 int num, count = 0;
  • Take Number to check as input from User and save it in Variable “num”.
cout << " Number to Check ";
	cin>> num;
  • Check the number whether it is Prime or Not using for() Loop.
 for (int a = 1; a <= num; a++) 
    {
        if (num % a == 0) 
        {
            count++;
        }
    }
  • Print the Ouput
if (count == 2) 
    {
        cout<<" "<<num<<" is a prime number.";
    }
    else {
        cout<<" "<<num<<" is not a prime number.";
    }

Code : To Check Prime Number

#include <iostream>
using namespace std;
int main()
{
    int num, count = 0;
	cout << " Number to Check ";
	cin>> num;	
    for (int a = 1; a <= num; a++) 
    {
        if (num % a == 0) 
        {
            count++;
        }
    }
    if (count == 2) 
    {
        cout<<" "<<num<<" is a prime number.";
    }
    else {
        cout<<" "<<num<<" is not a prime number.";
    }
    return 0;
}

Output

Leave a Reply