Wednesday 16 October 2019

Prime Number Program in C++

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 the user to enter a number and start checking for prime number. Here we write code Prime Number Program in C++
Prime number program in C++

If the number is divisible by 2 to one less than that number (n-1), then the number is not a 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 compiled and executed, it will produce the following result. Above C++ Programming Example Output (for prime number):

Output
Enter a Number 17 This is a prime number
Enter a Number 20 This is not a prime number

No comments:

Post a Comment