Loops

Last updated Sunday, November 18, 2001.

 

Simple "pre-test" loops

These are loops in which the test for continuation takes place each time the loop cycles back to the beginning. Since the test takes place at the start of each iteration, it is possible that the statements inside the loop will not be executed.

C,
C++,
C#,
Java

while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the start of each iteration.

while (testCondition)
    statement(s)

 

Example

The following code prints a countdown from 10 to 1. Assume that a function called display() has been defined. Assume that it's the same thing as printf() in C, cout in C++, System.Console.WriteLine() in C# and System.out.println() in Java.

int count = 10;
while (count > 0) {
    display(count);
    count--;
}

Python

while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the start of each iteration.

while testCondition:
    statement(s)

 

Example

The following code prints a countdown from 10 to 1.

count = 10
while count > 0:
    print count
    count = count - 1

RB

do until loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to FALSE at the start of each iteration.

do until testCondition
    statement(s)
loop

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
do until count = 0
    msgbox str(count)
    count = count - 1
loop

 

while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the start of each iteration.

while testCondition
    statement(s)
wend

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
while count > 0
    msgbox str(count)
    count = count - 1
wend

VB 6, VB .NET

do until loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to FALSE at the start of each iteration.

Do Until testCondition
    statement(s)
Loop

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
do until count = 0
    msgbox str(count)
    count = count - 1
loop

 

do while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the start of each iteration.

Do While testCondition
    statement(s)
Loop

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
do while count > 0
    msgbox str(count)
    count = count - 1
loop

 

while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the start of each iteration. This loop differs slightly in VB6 and VB .NET.

' VB6
While
testCondition
    statement(s)
Wend

' VB .NET
While
testCondition
    statement(s)
End While

Note that the end of a while loop is the non-word wend in VB6 and the more consistent end while in VB .NET.

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
while count > 0
    msgbox str(count)
    count = count - 1
wend 'end while in VB .NET

 

While, wend and end while

For those of you using RB and VB6, Hardcore Visual Basic has this to say about the old-school While loop (the one that uses the Wend keyword):

"There's nothing terribly wrong with the While/Wend looping structure of Basic, other than the ugliness of the pseudoword Wend. Some people on the Visual Basic team suggested changing Wend to the more consistent End While for version 5...they should have ripped [it] out of the documentation but kept it in the language for compatibility. Why waste your coding energy on a vague feature when Basic offers a clear, concise one? The Do Loop control structure of Basic is a thing of elegance compared with the crude looping of C and Pascal. You can test at the beginning or at the end for true or false conditions in a natural, English-like way. Perpetual loops can be coded clearly instead of requiring an ugly hack such as Pascal's While (True) or C's for(;;)...I admit that this is an aesthetic preference with no connection to efficiency or correctness." (Hardcore Visual Basic, Second Edition, p. 3)

Looks like Microsoft finally got it right with VB.NET. REAL Software, it's your turn...

 

Simple "post-test" loops

These are loops in which the test for continuation takes place each time the loop reached the end. Since the test takes place at the end of each iteration, the statements inside the loop will be executed at least once.

C,
C++,
C#,
Java

do...while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the end of each iteration.

do something
    statement(s)
while (testCondition);

 

Example

The following code prints a countdown from 10 to 1.

int count = 10;
do {
    display(count);
    count = count - 1;
}
while (count >= 1);

Python

Use while loops with a break statement

Python has no "post-test" loops. Rewrite the loop so that if performs the test at the start, or if you must perform the test at the end, use an if statement containing a break at the end of a loop.

Example

The following code prints a countdown from 10 to 1.

count = 10
while 1:
    print count
    count = count - 1
    if count < 1:
        break

RB

do...until loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to FALSE at the end of each iteration.

do
    statement(s)
loop until testCondition

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
do
    msgbox str(count)
    count = count - 1
loop until count < 1

VB 6, VB .NET

do...loop until loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to FALSE at the end of each iteration.

Do
  something
Loop Until testCondition

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
do
    msgbox str(count)
    count = count - 1
loop until count < 1

 

do...loop while loop

The set of statements in the loop are executed repeatedly as long as the test condition evaluates to TRUE at the end of each iteration.

Do
  something
Loop While testCondition

 

Example

The following code prints a countdown from 10 to 1.

dim count as integer
count = 10
do
    msgbox str(count)
    count = count - 1
loop while count >= 1

 

For loop

C,
C++,
C#,
Java

for loop

The basic for loop has the following structure:

for (counter = startValue; continueCondition; change)
    statement(s)

A one-time variable initialization is performed at the start of the loop. Each time the loop cycles to the beginning, the continueCondition is evaluated. The statement(s) are execute if and only if the continueCondition evaluates to true.

Counting upwards from a to b:

for (i = a; i <= b; i++)
    statement(s)

Counting downwards from a to b:

for (i = a; i >= b; i --)
    statement(s)

Python

for loop

The for loop has the following structure:

for currentItem in sequence
    statement(s)

Python's for loop is different from most other languages' versions. While the for loop in most programming languages makes a variable count from a start value to an end value, Python's for loop sets a variable to iterates through a sequence of items (such as a list or string). This approach, while unusual, is a good fit for a large number of programming tasks.

In order to make a Python for loop count like for loops in other languages, use Python's range() function to create a sequence of numbers through which it will iterate.

Counting upwards from a to b:

for i in range(a, b+1):
    statement(s)

Counting downwards from a to b:

for i in range(a, b-1, -1):
    statement(s)

RB

For loop

The for loop has the following structure:

for counter = startValue to endValue [step stepSize]
    statement(s)
next

Counting upwards from a to b:

for i = a to b
    statement(s)
next

Counting downwards from a to b:

for i = a downto b
    statement(s)
next

VB

For loop

The for loop has the following structure:

for counter = startValue to endValue [step stepSize]
    statement(s)
next [counter]

Counting upwards from a to b:

For i = a To b
    statement(s)
Next

Counting downwards from a to b:

For i = a To b Step -1
    statement(s)
Next

 

foreach/For Each loop

C,
C++,
Java

No equivalent.

C#

foreach loop

foreach (item in group)
    statement(s)

The group can be any container class that supports the IEnumerable interface (such as arrays and collection classes).

 

Example

The following code creates an array of numbers and then uses a foreach loop to print them out.

int[] myNumbers = {2, 4, 6, 8, 10}
foreach (int currentNumber in myNumbers) {
    Console.WriteLine(temp);
}

Note that changing the contents variable holding the current item will not change the item in the group you're iterating through:

int[] myNumbers = {2, 4, 6, 8, 10}
foreach (int currentNumber in myNumbers) {
   currentNumber++;
   Console.WriteLine(temp);
}

Python

for loop

Python's for loop is equivalent to other languages' foreach loops.

for currentItem in sequence
    statement(s)

The group can be any sequence (strings, lists and tuples are sequences).

RB

No equivalent.

VB 6, VB .NET

For Each loop

The for each loop has the following structure:

for each item in group
    statement(s)
next

The group can be a collection or an array. The statement(s) are executed if and only if the group contains at least one element -- if it's empty or hasn't yet been dimensioned, the result is an error.

 

 

Breaking out of loops

Each of the languages covered by The Rosetta Stone has a statement for exiting from the middle of a loop. When this keyword is used, program control is transferred to the line immediately following the end of the loop.

C,
C++,
C#

break statement

When encountered inside a loop, program control is transferred to the line immediately following the end of the loop.

start of loop
    break;
end of loop

while (porridge > 0) {

    // some code here

    if (bearsAreNearby())
        break;

    // more code here

}

Java

break statement

When encountered inside a loop, program control is transferred to the line immediately following the end of the loop.

Java's break statement is more versatile than those for the other C-based languages, since it supports named breaks.

Python

break statement

When encountered inside a loop, program control is transferred to the line immediately following the end of the loop.

RB

Exit statement

When encountered inside a loop, program control is transferred to the line immediately following the end of the loop.

Exit

VB

Exit Do statement

When encountered inside a do loop, program control is transferred to the line immediately following the end of the loop.

Exit Do

 

Exit For statement

When encountered inside a for loop, program control is transferred to the line immediately following the end of the loop.

Exit For

 

C-based languages,
Python

for (int i = 1; i <= 10; i++) {

    // Code that we want to use
    //
whether i is even or odd

    if (i % 2 = 1)
        continue;

    // Code that we want to use
    // only if i is even


}

 

The C-based languages and Python also provide the continue keyword, which transfers program control to the beginning of the loop. This is useful if there are circumstances where you want program control to stay in the loop but avoid using some of its code. In the example below, we want to use the loop 10 times, but use a specific part of the loop code only if the iterator is even.

C-based languages,
Python

for (int i = 1; i <= 10; i++) {

    // Code that we want to use
    //
whether i is even or odd

    if (i % 2 = 1)
        continue;

    // Code that we want to use
    // only if i is even


}

 

In VB6, the Do and For loops each have their own statement for breaking out of them. The Do loop has Exit Do and the For loop has Exit For. For some strange reason, there is no corresponding Exit While for the While loop; this is one of those rare circumstances where the use of goto is appropriate.