while Repetition Statement
A repetition structure (also known as a loop) allows the programmer to specify that a script is to repeat an action while some condition remains true. The pseudocode statement
While there are more items on my shopping list
Purchase next item and cross it off my list
describes the repetition that occurs during a shopping trip. The condition “there are more items on my shopping list” may be true or false. If it’s true, then the action “Purchase next item and cross it off my list” is performed. This action is performed repeatedly while the condition remains true. The statement(s) contained in the While repetition structure con-stitute its body. The body of a loop such as the While structure may be a single statement or a block. Eventually, the condition becomes false (i.e., when the last item on the shop-ping list has been purchased and crossed off the list). At this point, the repetition termi-nates, and the first pseudocode statement after the repetition structure executes.
As an example of a while statement, consider a program segment designed to find the first power of 2 larger than 1000. Variable product begins with the value 2. The statement is as follows:
var product = 2;
while ( product <= 1000 ) product = 2 * product;
When the while statement finishes executing, product contains the result 1024. The flowchart in Fig. 7.5 illustrates the flow of control of the preceding while repetition state-ment. Once again, note that (besides small circles and arrows) the flowchart contains only a rectangle symbol and a diamond symbol.
When the script enters the while statement, product is 2. The script repeatedly mul-tiplies variable product by 2, so product takes on the values 4, 8, 16, 32, 64, 128, 256, 512 and 1024 successively. When product becomes 1024, the condition product <= 1000 in the while statement becomes false. This terminates the repetition, with 1024 as product’s final value. Execution continues with the next statement after the while state-ment. [Note: If a while statement’s condition is initially false, the body statement(s) will never execute.]
The flowchart clearly shows the repetition. The flowline emerging from the rectangle wraps back to the decision, which the script tests each time through the loop until the deci-sion eventually becomes false. At this point, the while statement exits, and control passes to the next statement in the program.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.