Simple Program for Copy Constructor Example 2 Using C++ Programming

To calculate factorial of a given number using the copy constructor.

Definition of Factorial

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

For example,

6! = 6 x 5 x 4 x 3 x 2 x 1 = 720

The value of 0! is 1, according to the convention for an empty product.

Simple Program Copy Constructor Algorithm/Steps:

  • 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 the argument to assign the value.
  • STEP 4:  To call the function calculate() do the following steps.
  • STEP 5:   For i=1 to var
  • 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.

Simple Program for Copy Constructor

#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();
}

Sample Output

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