# C++ program to find the factorial of a number using class

Given a number, we have to find its factorial using class and object approach.
Submitted by Shubh Pachori, on August 04, 2022

Example:

```Input: Enter Number: 5
Output: Factorial of 5 is 120
```

## C++ Code to find out the factorial of a number using class and object approach

```#include <iostream>
using namespace std;

// create a class
class Factorial {
// declare a private data member
private:
int number;

// a public function with a int type parameter
public:
void factorial(int n) {
// copying the value of parameter in data member
number = n;

// declare two int type variable for operating
int index, factorial = 1;

// for loop to find factorial of the number
for (index = number; index >= 1; index--) {
// multiply the number in the factorial
factorial *= index;
}

// printing the factorial
cout << "Factorial of " << number << " is " << factorial << endl;
}
};

int main() {
// create a object
Factorial F;

// declare a int type variable to store number
int n;

cout << "Enter Number: ";
cin >> n;

// calling function by object
F.factorial(n);

return 0;
}
```

Output

```Enter Number: 5
Factorial of 5 is 120
```

Explanation:

In the above code, we have created a class Factorial, one int type data member number to store the number, and a public member function factorial() to find the factorial of the given integer number.

In the main() function, we are creating an object F of class Factorial, reading an integer number by the user, and finally calling the factorial() member function to find the factorial of the given integer number. The factorial() function contains the logic to find the factorial of the given number and printing the result.

What's New

Top Interview Coding Problems/Challenges!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates