Sometimes in our programs we have some code that we need to repeat for a specific number of times.
VBScript offers us a number of looping constructs that we can use to repeat code in our programs. In this lesson we will see the use of While Loop.
The While Loop is used to repeat a block of code while a given condition is true.
Here is an example:
counter = 0
While counter <= 10
document.write("Loop Iteration No. " & counter & "<br>")
counter = counter + 1
Here is the output:
Loop Iteration No. 0
Loop Iteration No. 1
Loop Iteration No. 2
Loop Iteration No. 3
Loop Iteration No. 4
Loop Iteration No. 5
Loop Iteration No. 6
Loop Iteration No. 7
Loop Iteration No. 8
Loop Iteration No. 9
Loop Iteration No. 10
Here is how the above code works:
- We start by declaring a variable named counter and then setting it to 0.
- Next we use the While keyword to start the While loop followed by the condition i.e. counter <= 10. The condition asks the VBScript interpreter to repeat the code contained in the While loop untill the value of the variable named counter is less than or equal to 10.
- The next two lines are the actual code that gets executed on each iteration of the loop. We call every loop repetition an iteration of the loop. The first line outputs the loop iteration number and the second line increments the counter variable by one.
- At the end of each loop iteration the VbScript interpreter checks to see if the loop condition is still true, if it find it to be true the loop code block is executed otherwise the control transfers to the line immediately after the Wend keyword.
Next >>> Lesson No. 12: VBScript For Loop