Answer to Question #100845 in C++ for Q3

Question #100845
Write a program that will display the result of n! using a loop. For example,if the user enters 5 for
n, the program should display “factorial of is 120”. solve with dowhile
1
Expert's answer
2020-01-02T11:26:26-0500

If you want to understand the essence of the code, I highly recommend using the code below with explanatory comments.

If you want to get a “clean” code without comments, then copy the code that is presented below.

Link to the archive with the code .cpp:

https://drive.google.com/drive/folders/1T0hzHv5-qMoKyu9ZPlzXp2i9sKeyqmZO?usp=sharing


Thanks!



CODE WITH COMMENTS:


#include <iostream>
using namespace std;
int main()
{
	long long result = 1; 
    //Result of calculations.The data type for the result 
    //must be able to store very large values.
     int n = 0; //Valuse for n!
      
      	cout << "Enter value > "; cin >> n;
      	if (n < 0)
      	{
      		cout << "\n" << "Too small value!" << "\n\n";
      		return -1; 
      		//If the main () function returns -1, 
            //this means that the program terminated with errors.
      	}
// n = 20 - the maximum value for factorial that can be stored by data type long long
      	else if (n > 20)
	{
		cout << "\n" << "Too big value!" << "\n\n";
		return -1;
	}
	
	int i = 0; // - counter
	if (n != 0) //Doesn't work with n = 0.
	{
		do 
		result *= ++i;
		while (i < n);
		//The result is sequentially multiplied by i, because by definition n! 
        //is the product of numbers from 1 to n.
		//Counter i is incremented by a prefix increment.  
        //This means that from the beginning the counter i increases, 
		//and then other actions are performed on it 
        //(the priority of the increase operation is higher than multiplication).
		//So, i increases from 0 to 1, and the result result is multiplied by i.
		//If i < n, ++i will be less or equal to n, which is what we need.
	}
	else
	{
		result = 1; //Some special value - 0! is  1.
	}
	cout << "\n" << "Factorial of " << n << " is " << result << ".\n\n";

	return 0;
}

-CODE ONLY-


#include <iostream>
using namespace std;
int main()
{
	long long result = 1;
	int n = 0;

	cout << "Enter value > "; cin >> n;
	if (n < 0)
	{
		cout << "\n" << "Too small value!" << "\n\n";
		return -1; 
	}
	else if (n > 20)
	{
		cout << "\n" << "Too big value!" << "\n\n";
		return -1;
	}
	
	int i = 0;
	if (n != 0)
		do
		result *= ++i;
		while (i < n);
	else
		result = 1; //0! is  1.

	cout << "\n" << "Factorial of " << n << " is " << result << ".\n\n";

	return 0;
}









Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS