Please, put you code into a code block (# button) next time. Below you can see the solution:
#include <iostream>
using namespace std;
// Compute n! (known as a factorial)
void factorial(int n, int& result)
{
result = 1;
for( int i = n; i > 1; i-- ) // n * (n-1) * (n-2) * … * 2
{
result *= i;
}
}
int main()
{
int k, fact;
cout<<"Please enter an integer number"<<endl;
cin>>k;
// calculate factorial
factorial(k, fact);
cout<<"The result of "<<k<<"! is "<<fact<<endl;
return 0;
}
1) Factorial function changes, threating result as a local variable, but not declaring it.
2) No need to return the result.
3) main changes. Now we declare fact variable and pass it to factorial function.
The trick is when using a reference, local function variable (result) and calling function (main) variable (fact) are sharing the same memory! That's why when writing to the result variable, the fact variable automatically gets the same value.