How to do factorial for loop javascript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to do factorial for loop javascript

Hi I tried doing the question for a factorial for loop in JavaScript and I can't figure out what I'm doing wrong, I've looked round on google and I don't see why this doesn't work function main() { var number = parseInt(readLine(), 10) var factorial = 1; // Your code here for (;number>0; number--){ factorial *=} console.log(factorial) } It keeps saying one of the } is the problem and in honestly at a loss

19th Jan 2021, 9:37 PM
Adamjhw
Adamjhw - avatar
9 Answers
+ 1
the problem is this line: factorial *=} replace it with factorial *= number; }
19th Jan 2021, 10:32 PM
John Robotane
John Robotane - avatar
+ 1
Thank you, I tried that but now every answer is 0?
19th Jan 2021, 10:38 PM
Adamjhw
Adamjhw - avatar
+ 1
are you sure that the condition in your for loop is number > 0? I mean, may be you have number >=0 or something else.
19th Jan 2021, 10:44 PM
John Robotane
John Robotane - avatar
+ 1
Sorry, I have no clue what I did, but It worked thank you. Would you mind helping as well, when reading the code, I would imagine if number = 10, then why wouldn't the code do 9x8x7... Since the loop says to do -1 each time?
19th Jan 2021, 10:48 PM
Adamjhw
Adamjhw - avatar
+ 1
Adamjhw that's exactly what your code does. if number=10 then your code will calculate 10x9x8x...x1 it will start at 10 and end with 1 because 1-1=0 which will break the loop.
19th Jan 2021, 10:56 PM
John Robotane
John Robotane - avatar
+ 1
I know, but why doesnt the first one make it start at 9 rather than 10?
19th Jan 2021, 11:01 PM
Adamjhw
Adamjhw - avatar
+ 1
number is decreased only after the loop instructions have been executed. so, on the first iteration, the loop will compare number to 0: if number>0 then it will execute the loop body, here factorial *= number. and then execute number-- and redo what is said above.
19th Jan 2021, 11:09 PM
John Robotane
John Robotane - avatar
+ 1
function main() { var number = parseInt(readLine(), 10) var factorial = 1; // Your code here for (;number>0; number--){ factorial *= number} console.log(factorial) } -----This might be a little easier to understand------------ function main() { var i = parseInt(readLine(), 10) var factorial = 1; // Your code here for (;i>0; i--){ factorial *= i} console.log(factorial) }
19th Nov 2021, 8:14 AM
Darien Keenan
Darien Keenan - avatar
0
look at this ** Statement 3 increases a value (i++) each time the code block in the loop has been executed. ** from here https://www.sololearn.com/learning/1140/
19th Jan 2021, 11:11 PM
John Robotane
John Robotane - avatar