# C++ Program to Check Whether a Number is Prime or Not

## What Is Prime Number

A prime number is a positive integer that is exactly divisible by the 1 and the number itself.

1, 3, 5, 7, 11, 17, 19 are the examples of prime numbers from 1 to 20

### Example Prime Number

For example, 3 is a prime number because it is only divisible by 1 and 3, also 7 is a prime number because it is only divisible by 1 and the number itself 7.

So, 27 is not a prime number because it is divisible by 1, 3, 9, and 27.

MCQ: 2 is the only even number which is a prime number.

Related: C++ Program Factorial of a Number

## C++ Program Prime Number 1

```.wp-block-code {
max-width: 100%;
overflow: auto;
border: 0;
}

.wp-block-code > div {
width: 100%;
overflow: auto;
}
.wp-block-code > code {
width: 100%;
position: relative;
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
overflow-x: scroll;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```#include <iostream>
using namespace std;

int main() {
int i, n;
bool isPrime = true;

cout << "Enter a positive integer: ";
cin >> n;

// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
isPrime = false;
}
else {

// 2 is a prime number
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";

return 0;
}
```Code language: PHP (php)```

Also Read: C++ Program Factorial using Recursion

## Prime Number C++ Program 2

``````//C++ program to check for prime number
#include<iostream>
using namespace std;

int main()
{
int num, i, j = 0;

cout << "Enter number: ";
cin >> num;

//check for prime number
for (i = 1; i <= num; i++)
{
if ((num % i) == 0)
{
j++;
}
}

if (j == 2)
cout << "\n" << num << " is a prime number.\n";
else
cout << num << " is not a prime number.\n";

return 0;
}```Code language: PHP (php)```