- C++ program to find factorial using recursive function
- C++ program to convert binary number to decimal and decimal to binary
- C++ program to display prime numbers between two intervals
- C++ program to print Pascal’s and Floyd’s triangle
- C++ program to print star pyramid patterns
- C++ Hello World Program
- C++ program to display Fibonacci series using loop and recursion
- C++ program to find area of the circle
- C++ program to calculate the area of the square with and without using function
- C++ program to encrypt and decrypt the string
- C++ program to convert temperature
- C++ program to check prime number
- C++ program to check palindrome number
- C++ program to make simple calculator using switch case
- C++ program for time conversion (convert time format)
- C++ program to find GCD or HCF
- C++ program to check for the power of two
- C++ program to check Armstrong number
- C++ program to check leap year
- C++ program to find LCM of two numbers

In this program, you will learn about C++ program to check prime number in two different ways.

**First, let’s be clear about the prime number:**

A number is called prime number if it is divisible by 1 and itself only.

For example: 1, 3, 5, …., 91, ….

```
//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;
}
```

**Output**

**Explanation**

The logic of the above program is to check the number entered by the user is perfectly divisible by 1 and itself which is accomplished inside `for`

loop.

The iteration continues till the value of `i`

equals the number.

**Let’s check out another way of solving the same problem.**

```
//C++ program to check for prime number
#include<iostream>
using namespace std;
int main()
{
int num, i;
bool checkPrime = true; //value of checkPrime must be true or false
cout << "Enter number: ";
cin >> num;
//check for prime number
for (i = 2; i <= num / 2; ++i)
{
if ((num % i) == 0)
{
checkPrime = false;
break;
}
}
if (checkPrime)
cout << "\n" << num << " is a prime number.\n";
else
cout << "\n"<< num << " is not a prime number.\n";
return 0;
}
```

**Output**

Enter number: 42 42 is not a prime number Enter number: 29 29 is a prime number

**Explanation**

This program also checks whether the number entered by the user is perfectly divisible by `i`

or not.

In this case, we have declared and initialized boolean variable `checkPrime`

to `true`

. If the `num`

is perfectly divisible by `i`

then checkPrime is set to `false`

.