A program loop is a set of instructions that is executed repeatedly. We will distinguish between the For loops and While loops.
The For loop allows you to create a group of commands to be executed a st number of times through the use of a counter that tracks the number of times the command block has been run. The syntax for the For loop is:
where start is the starting value of the counter, condition is a Boolean expression that must be true for the loop to continue, and update specifies how the counter changes in value each time the command block is executed.
The following table of the values of sins and cosines is created by using the For loop:
The table is produced by the following JavaScript code:
HTML/JavaScript code | Comments |
---|---|
<script type="text/javascript"> document.write("<table border='1' cellpadding='5'>" + "<tr><th>Degrees</th>" + "<th>Sin(d)</th><th>Cos(d)</th></tr>"); for (d = 0; d <= 360; d += 20) { var x = Math.PI*d/180; document.write("<tr><td>" + d + "</td>" + "<td>" + Math.sin(x) + "</td>" + "<td>" + Math.cos(x) + "</td></tr>"); } document.write("</table>"); </script> | opening JavaScript opening the table of sins and cosins the first column of the table the last two columns the For loop running 19 times convert x into radians form the first column fill out the second column fill out the third column end of the For loop closing the table closing JavaScript |
Similar to the For loop, the While loop runs a command group as long as a specific conditions is satisfied, but it does not empty any counters. The general syntax of the While loop is:
where condition is a Boolean expression that can be either true or false. As long as the condition is true, the commands in the command block are executed.
The example below shows an application of the While loop to creating the following table of colors:
The table is produced by the following JavaScript code:
HTML/JavaScript code | Comments |
---|---|
<script type="text/javascript"> var colors = new Array(10); colors[0] = "green"; colors[1] = "blue"; colors[2] = "red"; colors[3] = "yellow"; colors[4] = "white"; colors[5] = "cyan"; colors[6] = "brown"; colors[7] = "magenta"; colors[8] = "lightblue"; colors[9] = "orange"; document.write("<table border='1' cellpadding='10'><tr>"); var i = 0; while (i <= 9) { document.write("<td bgcolor=" + colors[i] + "> </td>"); i++; } document.write("</tr></table>"); </script> | opening JavaScript creating array of colors opening a table creating a loop counter starting the loop writing HTML tags for a table cell updating the counter closing the While loop closing the table row and table closing JavaScript |