Javascript to generate squares of 1 to n numbers

By | May 29, 2017

This post contains the Javascript to generate squares of 1 to n numbers. This script accepts a number as the input and generates the squares of all ‘n’ numbers starting from 1. Please go through the video and images to understand how it works.

Input: A number n obtained using prompt
Output: A table of numbers from 1 to n and their squares

 

Suggested Read:

 

<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Square.html </title>
<script type="text/javascript">
function square()
{
var n=prompt ("Enter the limit 'n' to generate the table of numbers from 1 to n:","");
var msg="";
var res= "0";
for(var x= 1; x<=n;x++)
{
res = x * x;
msg = msg + " " + x + " * "+ x + " = " + res + "\n";
}
alert(msg);
} 
</script>
</head>
<body style = "background-color:lightblue" onload = "square();">
<h2 style="text-align:center;color:black"> Javascript to generate squares of 1 to 'N' numbers</h2>
</body>
</html>

 

Input – a screenshot of the browser.

Javascript to generate squares of n numbers - Input

 

Output showing squares for 1 to 5.

Javascript to generate squares of n numbers - Output

 

Output 2 – shows squares of 1 to 15

Output showing Javascript to display squares of n numbers

 

How to execute this script?

  1. Copy the code and save it in a text file with a .html extension.
  2. Open the same file through the browser.
  3. You will be asked to enter a number and result will be displayed.
  4. To check for another number, refresh the page and again enter a new number.

 

Video explains the execution of the javascript:





Author: Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. It has been 6 years since I have been publishing articles and enjoying every bit of it. I want to share knowledge and build a great community with people like you.

Suggested articles for you:

Did it help? Comment here..