How would I display the method along with the answer?
e.g. User input = 5,
then the code output is "5 * 4 * 3 * 2 * 1 = 120" ?
function factorial(n)
{
var result = n;
for (var i = 1; i < n; i ++)
{
result = i * result;
}
alert("The answer is " + result);
}
Any help is much appreciated
The output you are looking to achieve is a string instead of an integer solution. So you should include logic to build this string inside your function.
You are also calculating the factorial incorrectly.
Something like this gives the desired output:
function factorial(n)
{
var result = 1;
var output_string = "";
for (var i = n; i > 0; i --)
{
result *= i;
if(i!=1) {
output_string += i + " * ";
} else {
output_string += i;
}
}
output_string += " = " + result;
alert(output_string);
}