You are on page 1of 2

Example: Check Prime Number

#include <iostream>

using namespace std;

int main()

int n, i;

bool isPrime = true;

cout << "Enter a positive integer: ";

cin >> n;

for(i = 2; i <= n / 2; ++i)

if(n % i == 0)

isPrime = false;

break;

if (isPrime)

cout << "This is a prime number";

else

cout << "This is not a prime number";

return 0;
}

Check Prime or Not in C++

To check whether the number is a prime number or not a prime number in C++ programming,
you have to ask to the user to enter a number and start checking for prime number.

If number is divisible by 2 to one less than that number (n-1), then the number is not prime n
umber, otherwise it will be a prime number.

C++ Programming Code to Check Prime or Not

Following C++ program ask the user to enter a number to check whether it is a prime number
or not, then display it on the screen:

You might also like