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:
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;
}
Comments
Leave a comment