HTML and CSS Reference
In-Depth Information
EXAMPLE
6.9
<html>
<head>
<title>Nested loops</title>
</head>
<body>
<script type="text/javascript">
<!-- Hiding JavaScript from old browsers
1
var str = "@";
2
for ( var row = 0; row < 6; row++){
3
for ( var col=0; col < row; col++){
document.write(str);
}
4
document.write("<br />");
}
//-->
</script>
</body>
</html>
EXPLANATION
1
The variable
str
is assigned a string
“@”
.
2
The outer
for
loop is entered. The variable
row
is initialized to
0
. If the value of
row
is less than
6
, the loop block (in curly braces) is entered (i.e., go to line 3).
3
The inner
for
loop is entered. The variable
col
is initialized to
0
. If the value of
col
is less than the value of
row
, the loop block is entered and an
@
is displayed in the
browser. Next, the value of
col
will be incremented by 1, tested, and if still less
than the value of
row
, the loop block is entered, and another
@
displayed. When
this loop has completed, a row of
@
symbols will be displayed, and the statements
in the outer loop will start up again.
4
When the inner loop has completed looping, this line is executed, producing a
break in the rows (see Figure 6.8).
Figure 6.8
Nested loops: rows and columns. Output from Example 6.9.