JavaScript to Calculates the Squares and Cubes of the Numbers from 0 to 10

Aim:

Write a JavaScript that calculates the squares and cubes of the numbers from 0 to 10 and outputs HTML text that displays the resulting values in an HTML table format.

Explanation:

This program aims at demonstrating the usefulness of Java script in generating dynamic web pages using Javascript. Accepting user input as web page loads is also demonstrated in this program. This script also illustrates validation using Javascript.

Code:

Html

<html>
<script type=text/javascript src=2.js>
</script>
<body onload=sc()>
</body>
</html>

JavaScript

function sc()
{
rng=prompt('Enter the range'); res=rng.split("-"); if(res.length!=2)
{
alert("invalid range "); return;
}
first=parseInt(res[0]); second=parseInt(res[1]); if(first>second)
{
alert("invalid range "); return;

}
str="<table border=2><tr><th>Number</th><th>Square</th><th>Cube</th></tr>";

for(i=first;i<=second;i++)
{
str=str+"<tr><td>"+i+"<td>"+(i*i)+"<td>"+(i*i*i);
}
document.write(str);

}

Javascript functions used:

prompt() – The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. Note: When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.

The prompt() method returns the input value if the user clicks “OK”. If the user clicks “cancel” the method returns null

split() – The split() method is used to split a string into an array of substrings, and returns the new array. If an empty string (“”) is used as the separator, the string is split between each character. The split() method does not change the original string.

alert() – The alert() method displays an alert box with a specified message and an OK button. An alert box is often used if you want to make sure information comes through to the user. The alert box takes the focus away from the current window, and forces the browser to read the message. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.

document.write() – The write() method writes HTML expressions or JavaScript code to a document. The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

Leave a Comment