VBScript
VBScript introduction
VBScript basics
VBScript variables
VBScript procedures
VBScript popup boxes
VBScript conditions
VBScript loops
VBScript arrays
VBScript strings
VBScript date & time
VBScript summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Browser scripting

Javascript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

VBScript loops

Imagine you have to write a program which performs a repetitive task such as counting from 1 to 100. Coding 100 lines to do this task would be mundane. There has to be an easier way, right? This is where loops come into the picture. Loops are specifically designed to perform repetitive tasks with one set of code. Loops save alot of time.

This lesson focuses on:

The for next loop

The for next loop is used to repeat a task a set number of times.

Syntax:

for aVariable = numStart to numEnd step aVariableIncrement

code to be executed

next

Example:

<script type="text/vbscript">
for a = 1 to 10 step 2

document.write(a & " ")

next
</script>

Output:

1 3 5 7 9

In the above example, the for next loop specifies that a loop should loop 10 times and increment the looping variable by 2 each time. Within the loop body the statement document.write(a & " ") will print the current value of the looping variable through each iteration together with a single space.

The do while loop

The do while loop works differently then the for loop. The for loop repeats a segment of code a specific number of times, while the do while loop repeats a segment of code an unknown number of times.

Syntax:

do while condition

code to be executed

loop

Example:

<script type="text/javascript">
Dim num
num = 0

do while num < 30

num = num + 5
document.write(num & "<br />")

loop
</script>

Output:

5 10 15 20 25 30

In the above example, a variable named num is given the value 0. The condition in the while loop is that while num is less than 30, 5 should be added to num. Once the value of num is greater than 30, the loop will stop executing. The loop prints the current value of num followed by a line break through each iteration.

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments