02 Loops

One of the great things about programming is the ability to make the computer do repetitive and boring calculations. Most programming languages use FOR - NEXT loops, DO loops and While loops. Javascript also uses FOR loops. In Javascript While loops are like DO loops only the condition for exiting the loop is contained in the While line. First lets look at a FOR loop. Examine the Javascript code below.

for (cel = -20; cel <=100; cel+=5){

fahr = cel * 9/5 + 32

document.write( cel+ " \t" +"\t"+ fahr +"<br>")

}

This loop starts at -20, cel = -20, keeps going as long as cel is less than or equal to 100, cel <=100, and counts by 5s, cel+=5.

Java, Javascript (and C) use special brackets {} called "braces". The code within the braces is looped according to the conditions set out in the for line. The " \t" codes are tabs. These will not work until you ad an HTML code to your page:

Add the <PRE> tag just before the <SCRIPT LANGUAGE=JavaScript> tag.

Add the </PRE> tag just after the </SCRIPT> tag.

Try out the code listed above. You will find that the document looks nicer with a heading. Add this to the top of your Javascript:

document.write("Cel\t\tFahr"+"<br>")

The While loop gives the same output. Examine the code below:

cel=-20

while (cel<=100){

fahr = cel * 9/5 + 32

document.write( cel + " \t" +"\t"+ fahr +"<br>")

cel+=5

}

  • first cel is given an initial value: -20

  • the loop is started with the "while" syntax and will continue while cel <= 100

  • again the loop is contained by the braces {}

  • document.write prints the result of the calculation

  • cel+=5 increments cel by 5

Review

  • For and While loops can be used in Javascript

  • The code to be repeated must be contained within {}

  • For loops need to know 3 things at the outset

  • While loops only need one parameter to start

  • To increment by ones use ++, eg. for (cel = -20; cel <=100; cel++){ will increment by ones.

  • You must add the <PRE>, </PRE> tags to the HTML code for \t code to work

Practice

  1. Job 21: Produce a table showing equivalent temperatures in Fahrenheit (F), Celsius (C), and Kelvin (K) using a For loop. Display the temperatures from 25 degrees Fahrenheit to 100 degrees Fahrenheit in 5 degree intervals. Note that C = 5 / 9*(F-32) and K = C + 273. Don't forget to put a "header" multiline comment stating your name, the date and the job # into your code.

  2. Job 22: Produce a table showing equivalent temperatures in Fahrenheit (F), Celsius (C), and Kelvin (K) using a While loop. Display the temperatures from 25 degrees Fahrenheit to 100 degrees Fahrenheit in 5 degrees intervals. Note that C = 5 / 9*(F-32) and K = C + 273. Don't forget to add a title and a link back to your "main" or "index" page on each job you publish.