-11

I'm learning Java Script and there is an exercise about getting the factorial of number user has entered but for some reason I always get answer is = 1

here is my code :

<SCRIPT>
function factorial(num){

    for (n=1; n<=num; n++){

    return fact*n;
    }
}

var myNum, fact;

myNum = parseFloat(window.prompt('Enter positive integer : ',''));
fact = 1;
document.write('the factorial of the number is = '+ factorial(myNum));



</SCRIPT>
Boann
  • 48,794
  • 16
  • 117
  • 146

2 Answers2

5

The pictured code (please include actual code in the future, not screenshots of code) returns fact immediately:

for ( n = 1; n <= num; n++ ) {
  return fact * n;
}

since n starts at 1.

What you want is to include fact in the function, and multiply it as the loop goes along, then return:

function factorial(n) {
  var fact = 1;

  for ( n = 2; n <= num; n++ ) {
    fact = fact * n;
  }

  return fact;
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

The reason this is returning 1 is because in your loop above, you return the value on the very first iteration, so n is never greater than 1.

Joshua Dannemann
  • 2,003
  • 1
  • 14
  • 34