do…while Repetition Statement
The do…while repetition statement is similar to the while statement. In the while state-ment, the loop-continuation test occurs at the beginning of the loop, before the body of the loop executes. The do…while statement tests the loop-continuation condition after the loop body executes—therefore, the loop body always executes at least once. When a do…while terminates, execution continues with the statement after the while clause. Note that it is not necessary to use braces in a do…while statement if there is only one statement in the body. However, the braces usually are included, to avoid confusion be-tween the while and do…while statements. For example,
while ( condition )
normally is regarded as the header to a while statement. A do…while statement with no braces around a single-statement body appears as
while ( condition );
which can be confusing. The last line—while( condition );—may be misinterpreted by the reader as a while statement containing an empty statement (the semicolon by itself). Thus, to avoid confusion, the do…while statement with a one-statement body is often written as follows:
} while ( condition );
The script in Fig. 8.9 uses a do…while statement to display each of the six different XHTML heading types (h1 through h6). Line 12 declares control variable counter and initializes it to 1. Upon entering the do…while statement, lines 15–17 write a line of XHTML text in the document. The value of control variable counter is used to create the starting and ending header tags (e.g., <h1> and </h1>) and to create the line of text to dis-play (e.g., This is an h1 level head). Line 18 increments the counter before the loop-continuation test occurs at the bottom of the loop.
The do…while flowchart in Fig. 8.10 makes it clear that the loop-continuation test does not occur until the action executes at least once.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!-- Fig. 8.9: DoWhileTest.html -->
<!-- Using the do...while repetition statement. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<title>Using the do...while Repetition Statement</title>
var counter = 1;
document.writeln( "<h" + counter + ">This is " +
"an h" + counter + " level head" + "</h" +
counter + ">" );
} while ( counter <= 6 );
Fig. 8.9 | Using the do…while repetition statement.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.