###
__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:__

__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;

cout<<"Please enter a number\n";

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:__
Please enter a number

34

34 is not a prime number

__Output 2:__
Please enter a number

77

77 is not a prime number

__Output 3:__
Please enter a number

229

229 is a prime number

## No comments:

## Post a Comment