C++ Program To Check Whether A Number is Prime Or Not

Prime Number Definition:

A prime number is a natural number greater than 1 having no positive divisors other than 1 and itself. For example 11 is a prime number because it has only two divisors which are 1 and 11(itself). On the other hand, 6 is not a prime number because it has divisors more than two which are 1,2,3 and 6.

Program Logic:

Lets make logic for this program. To make logic first we think about the definition of prime number. It tells us a positive number having no divisor other than 1 and the number itself. So we would have to check number for its divisors. In C++ coding, we will use FOR loop to divide number by 1 up to number itself. Loop divides entered number with all lesser numbers but actually we want to check how many times it gets perfectly divided. Here a counter variable comes handy. We will increment the value of counter variable every time number gets perfectly divided. At the end, we will check value of  counter variable. For prime number its value should be 2 because prime numbers have only two divisors.

 Recommended reading: C++ Project For Student Management System

C++ Program To Check A Number is Prime Or Not:

#include<iostream>
using namespace std;
int main(){
	int num,count=0;
	cout<<"ENTER NUMBER: ";
	cin>>num;
	for(int i=1;i<=num;i++)
	{
		if (num%i==0)
		{
			count++;
		}	
	}
	if(count==2)
	{
		cout<<num<<" IS A PRIME NUMBER.";
	}
	else
	{
		cout<<num<<" IS NOT A PRIME NUMBER.";
	}
	return 0;
}

Program Output:

C++ Program To Check Whether A Number is Prime Or Not

 

Code Explanation:

  • First we declared two integer type variables named count and num. Counter variable is initialized to zero meaning there are no divisors at the moment.
  • After that we prompted the user to enter the number and stored its value in num variable.
  • Next, we took a FOR loop which will start from 1 up to number that has entered to check how many times number gets perfectly divided.
  • In FOR loop, we set an IF condition and placed counter (count++) variable in its body.
  • Whenever a number from 1 up to number which has been entered is perfectly divided then IF condition becomes true and counter variable is incremented.
  • After FOR loop, we used IF-ELSE statement to check the value of counter variable. To be prime number, its value should be 2 because prime number gets only two divisor which are 1 and the number itself.
  • If value of counter variable is something else then it is not prime number.

I hope now you can write a C++ program to find prime number.

 Recommended reading: C++ Program To Convert Decimal Number Into Binary

If you liked this article, then I would really appreciate if you follow us on Twitter and Facebook.

If you have any question then you can ask me in comments. I would like to answer them.

You can also Click Here to Download Exercise Files.