Factorial in CPP Using Class


Factorial in CPP Using Class

Program Description- Program that calculates factorial in cpp of a natural number. Further, a class Fact is declared in which there are two public integer  variables  which are n and i and a public function factorial() which takes integer variable as an argument and  and returns an integer. Furthermore, in main main() function the variable  f1  of type Fact is declared which calls the function factorial of  the Fact class with an argument and returns the factorial of a natural number.

#include<iostream>
using namespace std;
class Fact     // Fact class
{
public:   // Fact class variables
int n;
int i;
public:
int factorial(int); // Fact class functions
};
int Fact:: factorial(int n) // Definition of Fact’s class function factorial
{
int fact=1;
for(i=1; i<=n; i++)
{
fact= fact * i;
}
return fact;
}


int main()
{
Fact f1; // Declaration of object of type Fact
int factval1;
factval1= f1.factorial(5);// f1 object is calling function of Fact class
cout<< factval1; // Output
return 0;
}
________________________________________________
For output see the video

Related Posts  Factorial in C++ Video
Share to Your Friend
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Have any Question or Comment?

Leave a Reply