Essentials of Counter-Controlled Repetition
Counter-controlled repetition requires:
1. The name of a control variable (or loop counter).
2. The initial value of the control variable.
3. The increment (or decrement) by which the control variable is modified each time through the loop (also known as each iteration of the loop).
The condition that tests for the final value of the control variable to determine whether looping should continue.
To see the four elements of counter-controlled repetition, consider the simple script shown in Fig. 8.1, which displays lines of XHTML text that illustrate the seven different font sizes supported by XHTML. The declaration in line 12 names the control variable (counter), reserves space for it in memory and sets it to an initial value of 1. The declara-tion and initialization of counter could also have been accomplished by the following dec-laration and assignment statement:
var counter; // declare counter counter = 1; // initialize counter to 1
Lines 16–18 in the while statement write a paragraph element consisting of the string “XHTML font size” concatenated with the control variable counter’s value, which repre
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!-- Fig. 8.1: WhileCounter.html -->
<!-- Counter-controlled repetition. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
var counter = 1; // initialization
while ( counter <= 7 ) // repetition condition
document.writeln( "<p style = \"font-size: " +
counter + "ex\">XHTML font size " + counter + "ex</p>" );
++counter; // increment
} //end while
Fig. 8.1 | Counter-controlled repetition.
<p style = "font-size: 5ex">XHTML font size 5ex</p>
Line 19 in the while statement increments the control variable by 1 for each iteration of the loop (i.e., each time the body of the loop is performed). The loop-continuation con-dition (line 14) in the while statement tests whether the value of the control variable is less than or equal to 7 (the final value for which the condition is true). Note that the body of this while statement executes even when the control variable is 7. The loop terminates when the control variable exceeds 7 (i.e., counter becomes 8).
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.