For loop

For loop

We'll use the template window to demonstrate some other features of Javascript. In previous exercises you have written a sequence of Javascript instructions. The next structure to consider is a program loop. I.e. we want the program to repeat a sequence of instructions a number of times. We will use the multiplication tables to demonstrate this. The user will be prompted for a value to be used in the table. You have already met the alert() and confirm() methods, now the prompt() method.

Modify the javascript template to add the following code and add a button to test the function.

codeView.png
function test()
{
    var mTbl = prompt("Enter a number","5");
    var output = "";
    for (var i=1;i<=10;i++)
    {
       output += mTbl + " x " + i + " = " + mTbl*i + "<br>";
    }
    document.getElementById('output').innerHTML = output;
}

The statement output += something is a shorthand way of writing
(new) output = (old) output + something

multiplication.jpg

By default, the program will produce the 5 times table (the default value is the second property in the prompt method, the first is the prompt string).

You should always provide a default value, to avoid problems with unassigned variables.

The HTML tags have been added to the header and a <BR> statement ends each line of the table. The working part of this program is the statement for (var i=1;i<=10;i++) { ... }. The code within the curly braces are the statements that will be repeated. In plan words the for statement can be read as "for variable i = 1; to i less than or equal to 10; increment i). The last part of the statement i++ is Javascript (as well as Java and C++) shorthand for increment i. i.e.
(new) i = (old) i + 1

A for { .. } loop is used when it is known in advance how many times the program must loop. In this case 10.

AttachmentSize
loops-Ex1.htm847 bytes