|
So far you've just done once-through programs. The great power of computers and programming is that you can have the machine repeatedly do similar calculations over and over.
Here we start with the for loop, which is ideal for loops where you know the starting value, the ending value, and the increment to use to progress through the loop.
In the following example we will use a doubly nested loop - a loop inside another loop - to create a multiplication table. We will do this twice. The first way will use plain formatting via the <PRE> HTML tag as we have shown in previous examples.
The second multiplication table will use <TABLE> HTML formatting. This also demonstrates how JavaScript works with HTML. Just output text with the HTML formatting tags
The basic form for a for loop is:
for (initialize statement, end test, increment statement) { block of code ... }
The end test is a conditional statement, which will be discussed in more detail later.
Where:
Example:
work/forloop.html
<HTML> <BODY> <PRE> <SCRIPT LANGUAGE="JavaScript"> // use pre-formatted output for this multiplication table var i,j; // loop variables for (j=1; j<=10; j++) { for (i=1; i<=10; i++) { document.write("\t",i*j); } document.write("\n"); // end the line } </SCRIPT> </PRE> <TABLE BORDER=1 CELLPADDING=6> <SCRIPT LANGUAGE="JavaScript"> for (j=1; j<=10; j++) { document.write('<TR>'); for (i=1; i<=10; i++) { document.write('<TD ALIGN="RIGHT">',i*j,'</TD>'); } document.write("</TR>\n"); // end the line } </SCRIPT> </TABLE> </BODY> </HTML>