Sum of the series Using Constructor in C++.
The constructor T4Tutorails_Series(int number)
is a member function of the class T4Tutorails_Series
. The constructor T4Tutorails_Series(int number)
has the same name as the name of its class T4Tutorails_Series
.
- When a new object
obj(5)
of the classT4Tutorails_Series
is executed, the constructorT4Tutorails_Series(int number)
also executed automatically. - The constructor
T4Tutorails_Series(int number)
has no data type. Even we canβt use void also. - The constructor
T4Tutorails_Series(int number)
can have arguments. - The constructor
T4Tutorails_Series (int number)
can be only public. - There is no inheritance of the constructor
T4Tutorails_Series (int number)
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> using namespace std; class T4Tutorails_Series { public: T4Tutorails_Series (int number) { int k=9; int sum=0; cout<<"Please input the number of terms."; cin>>number; for(int i=1;i<=number;i++) { sum=sum+k; k=k*10+9; } cout<<"The sum of T4Tutorails_ Series is "<<sum; } }; int main() { T4Tutorails_Series obj(5); } |
Output
Please input the number of terms. 5
The sum of T4Tutorails_ Series is 111105.