### For/Next loops

For/Next loops enable you to evaluate a sequence of statements multiple times. This is unlike the If and Select statements where the program passes through each statement at most once during the formula's evaluation. For/Next loops are best when you know the number of times that the statements needs to be evaluated in advance.

#### The syntax of the For loop through examples

##### Sample 1

Suppose you want to reverse the {Customer.Customer Name} string. For example, "City Cyclists" becomes "stsilcyC ytiC".

    Rem Reverse a string version 1
    formula = ""
    Dim strLen
    strLen = Len ({Customer.Customer Name})
    Dim i
    For i = 1 To strLen
       Dim charPos
       charPos = strLen - i + 1
       formula = formula & _
                 Mid({Customer.Customer Name}, charPos, 1)
    Next i

Let us examine how this formula works assuming that the current value of the field {Customer.Customer Name} is "Clean Air". The variable strLen is assigned to be the length of "Clean Air", namely 9. At this time it is also typed to be a Number variable. The variable i is known as a For counter variable since its value changes with each iteration of the For loop. In other words, it is used to count the iterations of the loop. The For loop will iterate 9 times, during the first time, i is 1, then i is 2, then i is 3 and so on until finally i = 9. During the first iteration, the ninth character of {Customer.Customer Name} is appended to the empty special variable formula. As a result formula equals "r" after the first iteration. During the second iteration, the eighth character of {Customer.Customer Name} is appended to formula and so formula equals "ri". This continues until after the ninth iteration, formula equals, "riA naelC" which is the reversed string.

##### Sample 2

Here is a simpler version of the above formula, that uses a Step clause with a negative Step value of -1. For the "Clean Air" example, i is 9 for the first iteration, 8 for the second, 7 for the third and so on until it is 1 in the final iteration.

    Rem Reverse a string version 2
    formula = ""
    Dim i
    For i = Len ({Customer.Customer Name}) To 1 Step -1
       formula = formula + _
                 Mid({Customer.Customer Name}, i, 1)
    Next i

##### Sample 3

The simplest version is to use the built in function StrReverse:

    Rem Reverse a string version 3
    formula = StrReverse ({Customer.Customer Name})

The built in String functions in Seagate Crystal Reports 8 can handle many of the string processing applications which would traditionally be handled using a For/Next loop or some other kind of loop. However, For/Next loops provide the most flexibility and power in processing strings and arrays. This can be essential if the built-in functions do not cover your intended application.

Seagate Software, Inc. http://www.seagatesoftware.com Please send comments to: techpubs@seagatesoftware.com