Factorial fun JavaScript | Sololearn: Learn to code for FREE!


Factorial fun JavaScript

The case: A number's factorial is the product of all positive integers less than or equal to the number. Write a program that takes a number as input and outputs its factorial to the console. Sample Input 5 Sample Output 120 Explanation 5*4*3*2*1 = 120 My code: function main() { var number = parseInt(readLine(), 10) var factorial = 1; // controlle van sololearn for (; number >0; number--) { number*factorial } console.log (number); } The out put is 0 But why? What do I need to change to get the right number to show?

1/17/2021 12:49:55 PM

Martijn Greven

2 Answers

New Answer


U make some mistakes. U find the factorial but you didn't store in a variable. And u should print the factorial instead of number. Corrected code: var number = parseInt(prompt()); var factorial = 1; for (; number >0; number--) { factorial=number*factorial; } console.log (factorial);


number*factorial does nothing because the result is not saved in a variable. In addition you want to change the variable number which is used in the loop. This make no sense here. The solution looks i.e. like as follows: for (; number>0; number--) { factorial *= number; } console.log (factorial);