C++ Programs‎ > ‎

Simple Program for Copy Constructor Using C++ Programming


C++ Simple Example Programs For Beginners

This Example Programs Calculate Prime Number Using Copy Constructor

To calculate factorial of a given number using copy constructor.

ALGORITHM:

STEP 1:  Start the program.
STEP 2:  Declare the class name as Copy with data members and member functions.
STEP 3:  The constructor Copy() with argument to assign the value.
STEP 4:  To cal the function calculate() do the following steps.
STEP 5:   For i=1 to var do
STEP 6:   Calculate fact*i to assign to fact.
STEP 7:   Increment the value as 1.
STEP 8:   Return the value fact.
STEP 9:   Print the result.
STEP 10: Stop the program.

PROGRAM:

#include<iostream.h>
#include<conio.h>
class copy
{
              int var,fact;
              public:
 
                copy(int temp)
                {
                 var = temp;
                }
 
                double calculate()
                {
                            fact=1;
                            for(int i=1;i<=var;i++)
                            {
                            fact = fact * i;
                            }
                            return fact;                           
                }
};
void main()
{
    clrscr();
    int n;
    cout<<"\n\tEnter the Number : ";
    cin>>n;
    copy obj(n);
    copy cpy=obj;
    cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
    cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
    getch();
}                                                       

Output:

Enter the Number: 5
Factorial is: 120
Factorial is: 120