Computing factorials I am computing factorials as part of teaching myself C++. I am looking for feedback on efficiency, style and any bad practices I may be using.

#include &lt;iostream&gt;
#include &lt;climits&gt;

using namespace std;

int main()
{
    unsigned int number{ 0 };
    unsigned long long factorial{ 0 };
    cout &lt;&lt; "The factorial of a non-negative integer n is denoted as n! (n factorial)...\n" &lt;&lt;
        "Example: 5! = 5x4x3x2x1 = 120\n\n";

    cout &lt;&lt; "Enter a non-negative integer and we will compute the factorial: ";
    cin &gt;&gt; number;
    while (cin.rdstate() || number &lt; 0 || number &gt; LLONG_MAX)
    {
        cin.clear();
        cin.ignore(LLONG_MAX, '\n');//flush input buffer
        cout &lt;&lt; "The data entered was invalid. Try again?\n\n" &lt;&lt; endl;
        cout &lt;&lt; "Enter a non-negative integer and we will compute the factorial: ";
        cin &gt;&gt; number;
    }
    if (number == 0 || number == 1)//since 0! and 1! = 1 there is no need to do a calculation
    {
        cout &lt;&lt; "!" &lt;&lt; number &lt;&lt; " = 1" &lt;&lt; endl;
    }
    else
    {
        factorial = number * (number - 1);
        for (size_t i = 2; i &lt; number; ++i)
        {
            factorial *= (number - i);
        }
        cout &lt;&lt; number &lt;&lt; "! = " &lt;&lt; factorial &lt;&lt; endl;
    }
}
You should separate the computation code from the input/output code. As you have written it, the factorial computation code will never be reusable in any other program. To be specific, you should define an unsigned long long factorial(int n) function.

You have a formatting bug in the special case:


!0 = 1



In fact, you should structure your code to avoid the need for special cases altogether.

unsigned long long factorial(int n) {
    unsigned long long result = 1;
    while (n &gt; 1) {
        result *= n--;
    }
    return result;
}