Write a C++ program which perform the following:
1. Create a Class factorial
2. Create Private Member Variable and initialize it with Member
initialization list and with value zero
3. Now, take inputs from user
4. Create a Public Member Function Calculate( ) outside the class,
to calculate the factorial of a given input
5. Create another Public Member Function Result( ) outside the
class, to print the results on screen
6. Now, create a constant object of the class which perform following:
a. Passes the values to the Calculate( ) function
b. Call the Result( ) function to show result
#include <iostream>
class Factorial
{
mutable int factorial;
public:
Factorial() : factorial(0)
{
}
void Calculate(int v) const;
void Result() const;
};
void Factorial::Calculate(int v) const
{
factorial = 1;
if(v > 1)
{
for(int i = 1; i <= v; ++i)
{
factorial *= i;
}
}
}
void Factorial::Result() const
{
std::cout << "Factorial value is " << factorial << "\n";
}
int main()
{
int v;
std::cout << "Enter the value: ";
std::cin >> v;
if(!std::cin || v < 0)
{
std::cout << "Bad input\n";
return 1;
}
const Factorial obj;
obj.Calculate(v);
obj.Result();
return 0;
}
Comments
Leave a comment