4). Simple Constructor Example Program For Find Prime Number In C++

Prime Number Example Program,Simple Constructor Example Programs  In C++

Definition

In C++,Constructor is automatically called when object(instance of class) create.It is special member function of the class.
  • It has same name of class.
  • It must be a public member.
  • No Return Values.
  • Default constructors are called when constructors are not defined for the classes.

Syntax

class class-name
{
    Access Specifier:
        Member-Variables
        Member-Functions
    public:
        class-name()
        {
            // Constructor code 
        }
        
        ... other Variables & Functions
}

Algorithm:

STEP 1:  Start the program.
STEP 2:  Declare the class as Prime with data members,
                  Member functions.
STEP 3:  Consider the argument constructor Prime() with integer
                  Argument.
STEP 4:  To cal the function calculate() and do the following steps.
STEP 5:  For i=2 to a/2 do
STEP 6:  Check if a%i==0 then set k=0 and break.
STEP 7:  Else set k value as 1.
STEP 8:  Increment the value i as 1.
STEP 9:  Check whether the k value is 1 or 0.
STEP 10:If it is 1 then display the value is a prime number.
STEP 11:Else display the value is not prime.
STEP 12:Stop the program.

Example Program

/*  Example Program For Simple Constructor Example Program For Prime Number Overloading In C++
    little drops @ thiyagaraaj.com

    Coded By:THIYAGARAAJ MP             */

#include<iostream>
#include<conio.h>

using namespace std;

// Class Declaration
class prime
{
    //Member Varibale Declaration
int a,k,i;
public:

prime(int x)
{
a=x;

k=1;
{
for(i=2;i<=a/2;i++)
if(a%i==0)
{
k=0;
break;
}
else
{
k=1;
}
}
}

void show()
{
if(k==1)
cout<<"\n"<<a<<" is Prime Number.";
else
cout<<"\n"<<a<<" is Not Prime Numbers.";
}
};

//Main Function
int main()
{
int a;
cout<<"Enter the Number:";
cin>>a;

// Object Creation For Class
prime obj(a);

// Call Member Functions
obj.show();
getch();
return 0;
}


Sample Output

Enter the Number:7
7 is Prime Number.