"while" Statements

First, we'll look at the "while" statement. This statement creates a loop that executes as long as the test condition evaluates to "true". For example: while x is less than 7, execute the loop.

Remember, when using the "while" statement, you must always increase the value of the condition, and the loop will not execute if the condition is false in the beginning.

There are generally three types of looping constructs: A sentinel control loop loops until some condition is met; a counter control loop, that loops a specified number of times; and an iterator, that loops over some data structure such as an array and performs an operation on each member of that data structure. These three looping constructs are often associated with while statements, for statements, and iterator loop.

These three types of loops will be covered in the next three sections. This section will cover the sentinel control loop, implemented with a while statement.

The schema for a sentinel control loop is the following:

Process the initial input, and set the initial loop condition
Check the loop condition
Process the data for each iteration of the loop
Process the new input, and update the loop condition
End for loop

Program 42 - Schema for a Sentinel Control loop


The following JavaScript program shows an implementation of a sentinel control loop. In this plan, the user is asked to input, using the JavaScript prompt() function, a numeric value. The program then squares the number, uses the JavaScript alert() function to print the result back to the user, and prompts the user for the next number. This is repeated zero or more times until the users enters the sentinel value, -1, at which point the loop stops.


<script>
let inputValue = prompt("please enter a number, or -1 to stop")
while(inputValue != -1) {
alert(inputValue + " squared is " +
(inputValue * inputValue))
inputValue = prompt("please enter a number, or -1 to stop")
}
</script>

Program 43 - Implementation of a Sentinel Control loop in JavaScript


Source: Charles W. Kann III, https://www.oercommons.org/courses/programming-for-the-web-from-soup-to-nuts-implementing-a-complete-gis-web-page-using-html5-css-javascript-node-js-mongodb-and-open-layers/view
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.

Last modified: Tuesday, October 4, 2022, 2:43 PM