The while instruction is used in a program to implement what is called simple repetition. That means that you can use it if you wanted to carry out the same set of instructions many times over. Just say you wanted to calculate a deduction of 10% on all the items on sale in your shop and write the new price and the saving on each item. You might write a program like this:
price=promptNumber ("How much is the
item?")
while
(price !=0)
{
deduction=price * 0.1
saleprice=price - deduction
alert ("The sales price is £ " + saleprice + "and the
deduction is £" + deduction)
price=promptNumber ("How much is the item?")
}
This program will repeatedly ask the user to type in prices, and will calculate the new sales prices until the user finally enters a price of zero.
Copy the program into the box below and try it out.
Question: Is it possible to get stuck in a while loop
forever?
Answer: Yes. If the test never becomes false the computer will keep
repeating the set of instructions for as long as you keep the computer turned
on..
Question: Why is the sequence of instructions surrounded
by braces?
Answer: So it is clear where the sequence of instructions starts and
finishes.
Click on the Back button on the tool bar to return to where you were.
| List of Javascript lectures | Relevant JavaScript Practicals (17 - 19) |