Factorial Program in C++ using Classes

Lets start C++ Programming with a simple Factorial program using Classes. Classes are nothing but a structure in ‘C’ Language which supports functions. We can write this program very simply within the main function but our main aim is to get started to use Classes and Objects.

In the program below, We are using defining a class with name Factorial. Then we have declared f and n variables as int data type, We then define fact and display functions under the access specifier Public (That means these functions/variables can be used anywhere throughout the program). fact() function communicates with the class with the help of ‘::‘ -> scope resolution operator. We have defined objects in the main function, Objects can be referred as variables of a Structure.

Factorial Program in C++ using Classes and Objects

#include<iostream.h>
#include<conio.h>

class factorial{
	int f, n;
	public:
	void fact();
	void display();
};

void factorial::fact()
{
	f=1;
	cout<<"\nEnter a Number:";
	cin>>n;
	for(int i=1;i<=n;i++)
		f=f*i;
}

void factorial::display()
{
	cout<<"\nFactorial of "<<n<<" is "<<f;
}

void main()
{
	clrscr();
	factorial ob;
	ob.fact();
	ob.display();
	getch();
}

Download Source Code

Factorial Program in C++ without using Classes and Objects

#include<iostream.h>
#include<conio.h>

void main()
{
	int f, n;
	clrscr();
	cout<<"\nEnter a Number:";
	cin>>n;
	f=1;
	for(int i=1;i<=n;i++)
		f=f*i;
	cout<<"\nFactorial of "<<n<<" is "<<f;
	getch();
}

Download Source Code

Output:
Factorial-Program-C-Output

Leave a Reply