Factorial in JavaScript - iteratively


Factorial iteratively

<!DOCTYPE html>
var n = prompt("n:", "");
var i = 1;
var s = 1;
while (i <= n) s *= i++;
alert(n + '! = ' + s);


 In the 1st line of the program, we inform the browser that our document was written in HTML (more precisely, it is an HTML 5 header). Line 2 contains the <html> tag that begins the HTML code. The 3rd line starts the <body> section of our document, containing the elements that are to appear on the page. In our example, the <body> section contains only a script written in JavaScript that implements an iterative factorial calculation algorithm. The <script> tag from line 4 informs about the start of the script - we can treat it as the starting block (1) of our algorithm.   The content of the script is contained in lines 5 to 9.
 In line 5, we declare a variable n using the var keyword, while the assignment operator ("=") initializes this variable with the value entered by the user using the prompt() statement, block (2) of the algorithm. prompt - JavaScript standard function - displays a text input pop-up on the screen. The first argument of the function specifies the text displayed as a prompt, the second is the default value entered in the edit field. In our case, we're displaying "n:" as the prompt, and we're not prompting the user with any default text (the second argument is the empty text ""). As a result, the prompt() function returns the text entered by the user into the edit field and then confirmed with the OK button.
In lines 6 and 7 we declare the variables i and s initializing them with the initial value (in both cases equal to 1), block (3) of the discussed algorithm.
 The while statement on line 8 is equivalent to the selection block (4) in our algorithm. The statement on the same line after the condition succinctly writes block (5). s*=i++ ; this notation means that variable s will be assigned its old value multiplied by the value of variable i, and then the value of variable i will be increased by 1. These statements will be executed as long as the condition in the while statement is met, i.e. as long as i is less than or equal to When n is continuously incremented and becomes greater than n, we go to the statement after the while loop, starting on line 9, where the result (6) is printed.
 The </script> tag from line 10 terminates the program (end of algorithm block (9)).
 Then, in lines 11 and 12, we close the </body> and </html> sections.