Q. C++ Program to Check Whether a Number is Prime or not.

Here you will find an algorithm and program in C++ programming language to check whether the given number is prime number or not. First let us understand what prime number means.

Explanation : A number that is divisible by only and only 1 and itself is known as a Prime Number. For example: - 11 is only divisible by 1, so 11 is prime, while 10 is divisible by 1, 2, and 5 so 10 is not a prime number.

Prime Number Algorithm

  Step 1 → Take integer variable A
  Step 2 → Divide the variable A with (A/2 to 2)
  Step 3 → If A is divisible by any value (A/2 to 2) then it is not prime
  Step 4 → Else it is prime number

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

#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;
	if (isPrime)
		cout << "This is a prime number";
		cout << "This is not a prime number";
	return 0;


Enter a positive integer : 17
This is a prime number.
Enter a positive integer : 25
This is not a prime number.