In this C++ tutorial, you will learn how to write a program to check if given number is a Prime number or not.

## Check if given Number is Prime Number Program in C++

To check if given number is prime number or not, check if there is any factor greater than 2. If any factor is found, then the given number is not prime. If there is no factor at all, then the given number is prime number.

## Program

In the following program, we read a number to n from user via console input, and check if there is any factor to decide whether the given number is prime number or not. We use C++ For Loop for iteration.

C++ Program

```#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number  : ";
cin >> n;

bool isPrime = true;
if (n == 0 || n == 1) {
isPrime = false;
}
else {
int i = 0;
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
cout << n << " is Prime Number." << endl;
} else {
cout << n << " is not a Prime Number." << endl;
}
}```

Output

```Enter a number  : 5
5 is Prime Number.
Program ended with exit code: 0```
```Enter a number  : 12
12 is not a Prime Number.
Program ended with exit code: 0```