The following is a program to find a factorial of a number using iteration in C++. To write this program, first of all, we need to understand the concept of factorial.

What is Factorial?

Factorial is represented by an exclamation mark (!). Factorial of n number is the product of all integers greater than or equal to 1 but less than or equal to n.

To find a factorial, the number should be greater than or equal to 1. Factorial of 0 is defined as 1 and factorial of a negative number is impossible.

Here is the source code of the program in C++ to Find Factorial of a Number using Iteration. This program is successfully compiled, and the output is also given below.

Program to find a factorial of a number using C++

#include<iostream>
using namespace std;
int fact(int n)
{
	int result=1;
	
	for(int i=1 ; i <= n ; i++)
	{
		result=result*i;
	}
	return result;
}
int main()
{
	int num;
	cout<<"Please Enter a Number to find its Factorial : ";
	cin>>num;
	
	if(num<0)
	{
		cout<<"\ninpossible to find the factorial, Please Try again";
	}
	else
	{
		cout<<"\nFactorial is :"<<fact(num);
	}
	
	return 0;
}

Output

Result of factorial using iteration

Program Explanation

The program starts execution forms the main method; first of all, we take a variable num to read the value from the user. if-else statements are used to check the variable if a positive number. If the num variable is negative, then factorial will be undefined and If section will execute. Otherwise else part will run.

In else section, fact() function is called by passing the num variable. Inside fact() function, a result variable is initialized to store the calculated value of factorial. Inside the for loop, the result variable is multiplied by the ‘i’ variable and after multiplication, the value will store back into result variable. This process is repeated until i <= num. As the condition of for loop got false, fact() function returns value of factorial.

Related Articles

Last modified: May 2, 2019