Home » C++ programs » C++ Most popular & searched programs

C++ program to find factorial of a number

In this program, we will learn how to find factorial of a given number using C++ program? Here, we will implement this program with and without using user define function.

Logic:

  1. Input a number
  2. Initialize the factorial variable with 1
  3. Initialize the loop counter with N (Run loop from number (N) to 1)
  4. Multiply the loop counter's value with factorial variable

Program to find factorial using loop in C++



#include <iostream>
using namespace std;

int main()
{	
	int num,i;
	long int fact=1;
	
	cout<<"Enter an integer number: ";
	cin>>num;
	
	for(i=num;i>=1;i--)
		fact=fact*i;
	
	cout<<"Factorial of "<<num<<" is = "<<fact<<endl;
	
	return 0;
}

Output

Enter an integer number: 6
Factorial of 6 is = 720

Program to find factorial using User Define Function in C++



#include <iostream>
using namespace std;

//function declaration
long int factorial(int n);

int main()
{	
	int num;
	
	cout<<"Enter an integer number: ";
	cin>>num;
	
	cout<<"Factorial of "<<num<<" is = "<<factorial(num)<<endl;
	
	return 0;
}


//function defintion
long int factorial(int n)
{
	int i,fact=1;
	
	for(i=n;i>=1;i--)
		fact=fact*i;
	
	return fact;
}





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





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


© https://www.includehelp.com some rights reserved.