Prime Number in C++

Here you learn how to check prime number in C++.

Prime number is a number which is only divided by 1 or itself.

Below is the C++ program to check whether a number is prime of not.

 

Prime Number in C++

#include<iostream>

using namespace std;

int main()
{
	int n,i,flag=1;
	cout<<"Enter any number:";
	cin>>n;
	
	for(i=2;i<=n/2;++i)
	{
		if(n%i==0)
		{
			flag=0;
			break;
		}
	}
	
	if(flag)
		cout<<"\n"<<n<<" is a Prime number";
	else
	cout<<"\n"<<n<<" is not a Prime number";

	return 0;
}

 

Output

Enter any number:7

7 is a Prime number

1 thought on “Prime Number in C++”

Leave a Comment

Your email address will not be published. Required fields are marked *