C++ program to check given number is prime or not. - coderforcoders

## Wednesday, 13 March 2019

### Prime number in C++

#### Theory:

Prime number in C++ is a simple C++ program to check a given number is prime number or not. A user will enter a number and the program will check whether the given number is prime number or not and outputs the result. Prime is a class declared and i, flags are the two data members of the class. int checkPrime() is the member function which is used to check whether the given number is prime number or not

#### Logic:

This program uses the concepts of  classes and objects. Prime numbers are the numbers which can completely divided only by the number 1 or by the same number itself. To check that, we are using for loop statement. The initioal value of variable flag will be zero and if the number is divided by any other number then the flag value turns to one. As per the program logic a number is a prime number only if the flag value is zero otherwise it is not a prime number.

flag=0;
for(i=2;i<=n/2;i++)
if(n%i==0)
flag=1;
if(flag==0)
return 1;
return 0;

#### Program:

C++ program to check given number is prime or not.

#include<iostream>
using namespace std;
class prime{
public:
int i,flag;
int checkPrime(int n)
{
flag=0;
for(i=2;i<=n/2;i++)
if(n%i==0)
flag=1;
if(flag==0)
return 1;
return 0;
}
};
int main()
{
int n,result;
prime obj1;
cin>>n;
result=obj1.checkPrime(n);
if(result)
cout<<n<<" is a prime number ";
else
cout<<n<<" is not a prime number ";
cout<<endl;
}

Output 1:
34
34 is not a prime number

Output 2: