Implementation of the division algorithm in JavaScript

<<algorithm

alg div en

<!DOCTYPE html>
<html>
<body>
<script>
var x=prompt("x:","");
var y=prompt("y:","");
if (y==0) alert("Can not divide by 0");
else {
  var z= x/y;
  alert("z = "+z);
};
</script> 
</body>
</html>

 

On line 1 of the program, we inform the browser that our document is written in HTML (it is precisely the header characteristic of HTML 5). Line 2 contains the <html> tag, which starts the HTML code. Line 3 begins the <body> section of our document, containing the elements that should appear on the page. In our example, the <body> section contains only a script written in JavaScript that implements the division algorithm for two numbers.

The <script> tag on line 4 signals the start of the script—we can treat this as the Start block (1) of our algorithm. The content of the script is contained in lines 5 through 11.

On line 5, using the keyword var, we declare the variable x—the dividend. Simultaneously, the assignment operator (=) initializes this variable with a value entered by the user using the prompt() instruction. prompt—a standard JavaScript function—displays a pop-up text input box on the screen. The function's first argument specifies the text displayed as the prompt, and the second is the default value entered into the edit field. In our case, we display the text "x:" as the prompt and do not suggest any default text to the user (the second argument is an empty string ""). The prompt() function returns the text entered by the user into the edit field and then confirmed with the OK button.

On line 6, we assign the value of the divisor to the variable y in an analogous way. Lines 5 and 6 correspond to the Input/Output block (2) of the discussed algorithm.

The conditional statement on line 7 is the Decision block (3) from our algorithm. The statement checks whether y is equal to 0. If the condition is met, the alert() instruction, written immediately after the condition, is executed (Input/Output block (4)). If the condition is not met, the instruction following the keyword else is executed; in our case, this is a compound statement enclosed in curly braces {} between lines 8 and 11. First, on line 9, we declare the variable z, to which we assign the value of the quotient of x divided by y (Operation block (5)), and then on line 10, we output the received result (Input/Output block (6)).

The </script> tag on line 12 ends the program's execution (Stop block of the algorithm (7)).

Finally, on lines 13 and 14, we close the </body> and </html> sections.