The C++ program mentioned here is able check whether the given number is Prime or not. To understand or code this program you need to understand what prime numbers are and how to find them.
A prime number is a number that has no positive divisors other than 1 and itself.
Complete definition, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A number that is not a prime is called composite, except 1 because 1 is considered neither a composite nor prime.
5 is a prime because only 1 and 5 can divide it, whereas 6 is a composite because it has the divisors 2 and 3 in addition to 1 and 6.
Example of prime numbers (between 1-100) : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.
How C++ program will find Prime numbers?
Suppose, the number we want to test is N then this program will divide the number N with all the numbers between 1 to N because if the number N is divisible by a number other then 1 or N then it’s not a prime.
Note: Actually we don’t really need to divide N up to N-1 to check if it is a prime or not because logically if there exist any number that can divide N then it can be find before N/2 division.
Suppose N is 35 then the program will divide 35 with 2, 3, 4, 5… up to 16 and check whether it is divisible by any of the number other than 1 and 37 or not. Here 35 is divisible by 5 and 7 therefore the program can easily tell that 35 is not a prime number.
C++ program code for prime number
Now we had learned about prime numbers and we will apply this knowledge into our C++ program for prime numbers.
// C++ program to check whether the given number is Prime or Not!
#include<iostream.h>
#include<conio.h>
void main()
{
int num, count=0;
clrscr();
cout<<"Enter a number :";
cin>>num;
for(int i=2; i<num/2; i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number";
else
cout<<"Not a Prime number";
getch();
}If you know what prime numbers are and knows a little programming then there is no need to explain this program but I am still going to explain a little about the program.
STEP1: The program is asking for a number, num.
STEP2: A loop starts from 2 to (num/2)-1 and divides num with these numbers,
If division is successful (when remainder is 0) then count is increased by 1 and loop ends (using break keywords).
STEP3: When the loop ends the value of count is checked for 0 (zero). 0 means no successful division and proves the number is prime.




