codescracker


c++

C++ Program to Check Prime or Not



« Previous Program Next Program »


Check Prime or Not in C++

To check whether the number is a prime number or not a prime number in C++ programming, you have to ask to the user to enter a number and start checking for prime number.

If number is divisible by 2 to one less than that number (n-1), then the number is not prime number, otherwise it will be a prime number.

C++ Programming Code to Check Prime or Not

Following C++ program ask the user to enter a number to check whether it is a prime number or not, then display it on the screen:

/* C++ Program - Check Prime or Not */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,i,count=0;
cout<<"Enter a number:";
cin>>num;
for(i=2;i<num;i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==0)
{
cout<<"This is a prime number";
}
else
{
cout<<"This is not a prime number";
}
getch();
}

When the above C++ program is compile and executed, it will produce the following result. Above C++ Programming Example Output (for prime number):

C++ program check prime number

Above C++ Programming Example Output (for not prime number):

prime number program c++ programming

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »


Latest 5 Posts by CodesCracker




Tools
Calculator

Quick Links
Signup - Login - Give Online Test