Skip to content
Science, Maths & Technology
Author:

# The while Sentinel

Updated Monday 29th June 2015

Learn to use sentinels within while statements to prevent infinite loops.

## Sentinels  Copyright free: Startupstockphotos via Pixabay In the examples used in 'Introducing the 'while' statement', the while loops acted as input guards, i.e. they required you to repeatedly input data values until an acceptable value was input. Another common use for while loops is in programs where some sort of repeated processing on a succession of data values is required, e.g. adding up the cost of all the items on a shopping list. In this sort of scenario, you don't generally know in advance how many data items there will be, so there needs to be some terminating value, which indicates to the program that there are no more items, as in the figure below. This special terminating value is sometimes called a sentinel. ## Activity 1

The purpose of this activity is for you to write a program where the user inputs strings one at a time, and the computer displays the strings on a single line separated by spaces. The processing continues until the user enters halt. The computer then displays Thank you on a new line.

For example, suppose the following seven strings were input:

Hello!, nice, to, interact, with, you, halt

The display would be as follows.

Hello! nice to interact with you
Thank you

Download our HTML template for a JavaScript program. Open the file in the text editor and add your program code. Test the program using some sequences of strings.

### Thinking about the program

The program reads in each word and processes it, until it comes to the sentinel (stopping value), which is the string 'halt'. The processing consists of displaying each string followed by a space, and then reading in the next string. When the sentinel is reached, Thank you is displayed on a new line.

### Writing the program

• How many variables do you need to hold the input data? Declare it/them.
• Write a JavaScript statement to read in the first data value.
• What is the sentinel (stopping value) of the while loop?
• What test has to be carried out on each data value to determine whether it is the sentinel? Write the condition for the while loop.
• What processing has to be done on each non-sentinel value? Write the body of the while loop.
• What processing has to be done after the sentinel is reached? Finish writing the program.
• Run and test the program.

### Solution

Here is our version of this code (though there are alternative correct solutions).

var word;
word = window.prompt('Please enter your first word','');
while (word != 'halt')
{
document.write(word + ' ');
word = window.prompt('Please enter next word or halt to end', '');
}
document.write('<BR>' + 'Thank you');

You can download our solution - sentinel_solution_1.html - if necessary.

Question:  Suppose the user enters halt in response to the prompt requesting the first word in the program in Activity 4.3.

(a) What will be the output from the program?

(b) How many times will the body of the while loop be executed?

### Answer

(a) The program will output only the Thank you line.
(b) The body of the while loop is not executed at all. Because the condition evaluates to false the first time it is tested, control will jump immediately to the line following the while loop.

Question: How would you change the code so that the sentinel is the word stop rather than the word halt?

### Answer

Change the condition of the while loop as follows:

while (word != 'stop')

## Activity 2

The following code is from sentinel_activity_2.html (with line numbers for reference).

(1)  var total, nextNumber;
(2)  total = 0;
(3)  document.write('The current value of the total is ' + total + '<BR>');
(4)  nextNumber = window.prompt('Please enter a positive number, any negative number to stop','');
(5)  nextNumber = parseFloat(nextNumber);
(6)  while (nextNumber >= 0)
(7)  {
(8)      document.write('Adding the new value of ' + nextNumber + '<BR>');
(9)      total = total + nextNumber;
(10)     document.write('The current value of the total is '
+ total + '<BR>');
(11)     nextNumber = window.prompt('Please enter a positive number, any negative number to stop','');
(12)     nextNumber = parseFloat(nextNumber);
(13) }
(14) document.write('The total sum of your numbers is ' + total);

Note that the output statements in lines (3), (8) and (10) are designed to show you the values of the variable total as the program executes. Including additional output statements is a useful way of tracing through your programs.

(a) Write down what you think the outputs will be when you input the numbers 3, 6, 4, –5 successively into the program. Run it in your browser and see whether you were correct. Briefly explain what the program does.

(b) Open sentinel_activity_2.html in your text editor if you have not already and insert // at the start of the lines which we've labelled (4) and (5) above. (This has the effect of telling JavaScript to treat these lines as comments, so that they will not be evaluated and is equivalent to deleting the lines.) Now save the file. What do you expect will happen when you run the program in your browser? Run the program with the same inputs as in part (a) to check whether you were correct.

(c) Again, open the file in your text editor. This time delete // from the start of lines (4) and (5), but comment out line (2) by inserting // at the beginning of the line. Save the file. What do you expect to happen when you run the program this time? Run it with inputs of 3, 6 and –5, and find out.

### Solution

(a) The output should be as follows.

The current value of the total is 0
Adding the new value of 3
The current value of the total is 3
Adding the new value of 6
The current value of the total is 9
Adding the new value of 4
The current value of the total is 13
The total sum of your numbers is 13

The program adds up a succession of positive numbers entered by the user. It displays the total when a negative number is entered.

The first line is the output from line (3) of the code.

You input 3 in response to line (4).

The test in line (6) evaluates to true, so the body of the loop is executed. The values of the new number entered and the new total are displayed, and you are asked to input another number.

In response to line (11), you input 6.

Execution returns to line (6). The condition still evaluates to true, so the body is executed again, resulting in the display of the next number input and the total; then you are asked to input another number.

In response to the input of 4, the loop body is executed once more and you input –5.

Execution returns to line (6). Now the test evaluates to false (as –5 is not greater than or equal to 0), so execution skips the body of the while loop and continues with line (14), giving the final display.

(b) You should get the following output.

The current value of the total is 0
The total sum of your numbers is 0

If lines (4) and (5) are deleted, no value is assigned to nextNumber and so, when the condition is tested at line 6, JavaScript cannot compare it with 0, as required. In this situation JavaScript simply returns false. Hence the body of the while loop is skipped, and line (14) executed (with total having the value assigned to it in line (2), i.e. 0).

(c) With inputs of 3, 6 and –5, you should get the following output.

The current value of the total is undefined
Adding the new value of 3
The current value of the total is NaN
Adding the new value of 6
The current value of the total is NaN
The total sum of your numbers is NaN

If line (2), which initialises the variable total, is deleted, the value of total is still undefined when line (3) is executed; hence the first line of output. When, in line (9), JavaScript tries to add a new value to this undefined variable, the current value of total is displayed as above.

Remember that NaN is JavaScript's abbreviation for 'Not a Number'!

Open the file in your text editor and modify it so that it multiplies together all the positive numbers you input, stopping when the sentinel 0 is input.

Hint: Take care with your initialisation.

### Solution

Here is our solution. (You may remember from studying mathematics at school or elsewhere that the result of multiplying two or more numbers together is called their product.)

var product, nextNumber;
product = 1;
document.write('The current value of the product is ' + product + '<BR>');
nextNumber = window.prompt('Please enter a positive number, 0 to stop','');
nextNumber = parseFloat(nextNumber);
while (nextNumber != 0)
{
document.write('Multiplying by ' + nextNumber + '<BR>');
product = product * nextNumber;
document.write('The current value of the product is ' + product + '<BR>');
nextNumber = window.prompt('Please enter a positive number, 0 to stop','');
nextNumber = parseFloat(nextNumber);
}
document.write('The product of your numbers is ' + product);

Note that initialising product to 0 wouldn't work as 0 multiplied by any other number will always give 0. You can download our solution - sentinel_solution_2.html - if required.

## Hints for writing programs with while loops

• Do you need any variables outside the loop to hold any data? If so, declare it/them. (You will probably need at least one variable for use in the condition which controls the loop.)
• Do you want any statements to be executed before the loop? (At the least, you may need to initialise the variable used in the condition.)
• What condition do you want to control the repetition of the loop body?
• What do you want to happen for each execution of the loop body?
• Does the body contain a statement or statements which will eventually cause the condition to evaluate to false? (If not, your program will go into an infinite loop.)
• Do you want any statements to be executed after the loop?

In the examples above, you have seen the repeated processing, using a while loop, of a succession of strings and of a succession of numbers. We now consider the repeated processing of a succession of characters within a string in the article 'More About Strings'

### Copyright information

For further information, take a look at our frequently asked questions which may give you the support you need.