Sum of square of n numbers using copy constructor

Q. Write a C++ program to calculate the value of following series using copy constructor and Inline member function.

S = 12 + 22 + 32 + 42 . . . + n2

Answer:


  • Copy constructor is used for creating the second object as defined in the above program.
  • In main() function, two objects are created using copy constructor. The program displays the Output: as per the series: S = 12 + 22 + 32 + 42 . . . + n2
    copy constructor inline member function execution
  • The above figure shows the actual execution of series and how it works using lnline member function and copy constructor.
Following program is calculating the value of above series (S = 12 + 22 + 32 + 42 . . . + n2) using copy constructor and Inline member function.

#include<iostream>
using namespace std;

class Series
{
        int num, i, sum;
    public:
        Series(int x)
        {
                num=x;
                sum=0;
        }
        Series (Series &x)
        {
                num=x.num;
                sum=0;
        }
        void calculate();
        void display();
};
inline void Series::calculate()
{
        for(i=1; i<=num; i++)
        {
                sum=sum+i*i;
        }
}
inline void Series::display()
{
        cout<<"\n Value of the Series : "<<sum;
}
int main()
{
        int x;
        cout<<"\n Enter Value : ";
        cin>>x;

        Series se1(x);
        se1.calculate();
        se1.display();

        Series se2(se1);
        se2.calculate();
        se2.calculate();

        return 0;
}


Output:

copy constructor inline member function