while

Below is a practical example of using a while loop. The loop will convert 3 sterling amounts into dollar amounts using the exchange rate of 1 pound sterling to 1.70 dollars.

function SterlingToDollars()
{
 dollars = new Array()
 sterling = new Array()
 sterling[1] = 23
 sterling[2] = 17.50
 sterling[3] = 75
 var exchangeRate = 1.70
 var loopCounter = 1
 while (loopCounter <= 3)
 {
  dollars[loopCounter] = sterling[loopCounter] * exchangeRate
  Debug.trace( sterling[loopCounter] + " = " + dollars[loopCounter] + "\n" )
  loopCounter++
 }
}

In this example, the while loop starts at the count of 1, which is less than 3, so it runs the list of statements. The first statement does the conversion for the first amount of sterling (the array sterling[1]) into dollars and saves the amount in the dollars array (dollars[1]). The Debug.trace function shows the calculation in a Debug window. The last line of code increments the loop counter by one – this is important! If you do not increment the counter than the loop counter will always be 1 and the loop will run infinitely.

The second time the loop is run loopCounter is set to 2, which is still less than three, so the loop is run again and the second sterling value is calculated and the other lines of code are also run. The third time the loop is run loopCounter is now 3, which is equal to the 3 in the while expression, so this time through the loop is the last time the loop is run. Be careful - when the value in the while statement is matched, the statements in the list are still run for that time. If you do not write the code correctly, you may go through a loop one more time than you want.

Once a while loop has finished, the next line of code is executed.

Close