Skip to content
Science, Maths & Technology
Author:

Introducing the while statement

Updated Monday 29th June 2015

Learn how to start programming for repetition with the while statement.

Introduction

A man sits on a sofa, checking a laptop computer Copyright free image Icon Copyright free: Startupstockphotos via Pixabay This section aims to introduce you to the while statement (often called a while loop), which has the effect of repeating execution of one or more program statements while a certain condition remains true, in addition to increasing your knowledge of the behaviour of strings.

You may recall that in the article 'Conditionals and Compound Statements' we discussed a program for calculating a user's age from their year of birth and the current year. If the current year entered was before the year of birth, the program gave the user a second chance of inputting the two years. But if invalid data was entered again, the program simply returned a nonsensical answer – a negative age. Ideally, we would have wanted the program to repeatedly prompt the user for the two dates until they had provided valid input. This is the sort of thing that can be done using a while loop.


Activity 1

Our example while_activity_1.html does something similar to the scenario described above. Using the current year (2015 at the time of writing) and the user's year of birth, it works out whether the person is entitled to receive a concessionary rail fare for a particular journey (which we will assume is available to people aged 60 and over), and displays the relevant fare. Only years of birth between 1900 and 2015 (inclusive) are accepted as valid, and the user is repeatedly prompted until he or she enters a valid year.

Here is the JavaScript code, numbered for reference.

/****************************************************************/
/* Program to display the appropriate fare for a rail journey   */
/* Assumptions:                                                 */
/* The current year is 2015.                                    */
/* Only years of birth in the range 1900 to 2015 are            */
/* accepted as valid.                                           */
/* Passengers of 60 or more are eligible for a                  */
/* concessionary fare of £18.                                   */
/* Other passengers pay £25.                                    */
/****************************************************************/

(1)  var currentYear, yearOfBirth;
(2)  var age; // age this year
(3)  currentYear = 2015;
(4)  yearOfBirth = window.prompt('Please enter your year of birth','');
(5)  yearOfBirth = parseFloat(yearOfBirth);
     // loop while valid input has not been received
(6)  while (yearOfBirth < 1900 || yearOfBirth > 2015)
(7)  {
(8)     document.write('You must enter a year of birth between 1900 and 2015 (inclusive)' + '<BR>');
(9)     yearOfBirth = window.prompt('Please enter your year of birth', '');
(10)    yearOfBirth = parseFloat(yearOfBirth);
(11) }
(12) age = currentYear - yearOfBirth;
(13) if (age >= 60)
(14) {
(15)     document.write('You are eligible for a concessionary fare of £18');
(16) }
(17) else
(18) {
(19)     document.write('Your fare is £25');
(20) }

(a) Run the program several times, with a variety of correct and incorrect inputs. Try to determine what the while statement does.

(b) Suggest some test values for the program.

Solution

(a) You should have noticed that if you enter a valid year in response to the prompt in line (4), the statements on lines (8), (9) and (10) are ignored.

If, however, you enter an invalid year (less than 1900 or more than 2008), the statements on lines (8), (9) and (10) are repeatedly executed until you get it right. In other words, each time the Boolean condition in the while statement evaluates to true, the instructions in the body of the loop are repeated. Only when the condition evaluates to false does control jump to the line following the complete while statement, line (12).

Note the way that the initial statements requesting input and converting it into a number (lines (4) and (5)) are repeated inside the loop (as lines (9) and (10)). This is one typical way of using a while loop to repeat one or more instructions that didn’t achieve their purpose first time round.

Note also the use we have made of the two different commenting styles in this program.

Don’t worry if you found the code for this program a bit hard to follow. You will become more familiar with the structures as the course progresses.

(b) You need to test your program with some valid years – between 1900 and 2015 (inclusive) – and some invalid years (at least one before 1900 and at least one after 2008). The boundary values are 1899, 1900, 1901, 2014, 2015 and 2016.


The Syntax of the while Statement

The syntax is

while (Boolean condition/expression)
{
    one or more statements
}

The statement(s) which are repeated as long as the while condition evaluates to true are called the body of the while statement. The body usually consists of several statements, but, as discussed in Subsection 3.3, these statements must be wrapped together into a single compound statement using braces.

If the Boolean expression controlling a while loop evaluates to true,the whole of the body is executed. Then execution returns to the top of the while statement and the condition is tested again to see if it is still true. If it is, the body is executed again, and so on until the condition evaluates to false. The body of the while statement is then skipped over and execution of the rest of the program continues, as you can see in the figure below.

While loop process. Process statements before the while loop. Test: Does the Boolean expression evaluate to true? If it does, execute the body of the loop. If it does not, carry on with the rest of the program

Activity 2

while_activity_2.html contains a copy of the password-changing program that you were asked to write in 'Testing Programs'. Modify the program so that you are repeatedly prompted to enter a new password, and then retype it, until the two inputs match. A message is then displayed telling you that your password has been changed.

Hint: You will need to replace the if statement by a while statement.

Solution

Here is our code.

var password, repeatPassword;
password = window.prompt('Please enter your password','');
repeatPassword = window.prompt('Please re-enter your password','');
while (password != repeatPassword)
{
    document.write('Your passwords don\'t match' + '<BR>');
    password = window.prompt('Please enter your password','');
    repeatPassword = window.prompt('Please re-enter your password', '');
}
document.write('Thank you. Your password has been changed');

The if statement has been replaced by a while statement, with the initial prompts duplicated in its body. You can download our solution - while_solution_2.html - if you want to experiment with it further.

Question: What would be the effect of the following while loop, if your response to the prompt statement is to input 37?

myVar = window.prompt('Enter a number smaller than 30','');
myVar = parseFloat(myVar);
while (myVar > 30)
{
    document.write('Please enter a number smaller than 30!');
}

Warning!
We do not intend you to try executing this code on your computer, but if you do, you will probably find that the program causes your computer to display a warning message, or behave in a rather peculiar manner! You may be able to stop the script from running by responding to the message. If not, use the Windows task manager to stop your browser running.

How would you correct the code?

Answer

The program would have displayed the line:

Please enter a number smaller than 30!

over and over again, until you stopped the program running, as explained above. Although the program keeps asking the user for a number less than 30, there is no program statement in the body of the loop to read in this new input. So the value of myVar stays at 37 and the condition always evaluates to true. You will thus be stuck in a never ending (infinite) loop.

To correct the code you would need to include instructions in the body of the loop to read in the new input, assign it to myVar and convert it into a number. You could repeat the two lines from before the while loop, so that the loop body would contain the following additional code:

myVar = window.prompt('Enter a number smaller than 30','');
myVar = parseFloat(myVar);

Question: Can the body of a while loop consist of only a single statement?

Answer

Yes, provided the statement contains code that will eventually cause the while condition to evaluate to false. For example, the condition in the following code fragment will evaluate to false as soon as a positive number is input.

var myVar;
myVar = window.prompt('Enter a positive number','');
while (myVar <=0)
{
    myVar = window.prompt('Please enter a POSITIVE number','');
}
document.write('The positive number is ' + myVar);

In the examples you've seen so far, the while loops acted as input guards, i.e. they required you to repeatedly input data values until an acceptable value was input. But there are other uses of the while statement. We'll be covering another of these in the article 'The while Sentinel'.

 

Author

Ratings

Share

Related content (tags)

Copyright information

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

Have a question?