Crystal Reports  

For Loops (Crystal Syntax)

For loops enable you to evaluate a sequence of expressions multiple numbers of times. This is unlike the If and Select expressions where the program passes through each expression at most once during the formula's evaluation.

For loops are best when you know the number of times that the expressions needs to be evaluated in advance.

For Loop Syntax

Example 1

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

//Reverse a string version 1
Local StringVar str := "";
Local NumberVar strLen := 
   Length ({Customer.Customer Name});
Local NumberVar i;
For i := 1 To strLen Do
(
   Local NumberVar charPos := strLen - i + 1;
   str := str + {Customer.Customer Name}[charPos]
);
str

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. 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 string variable str. Thus str equals "r" after the first iteration. During the second iteration, the eighth character of {Customer.Customer Name} is appended to str and so str equals "ri". This continues until after the ninth iteration, str equals, "riA naelC" which is the reversed string.

Example 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.

//Reverse a string version 2
Local StringVar str := "";
Local NumberVar strLen := 
   Length ({Customer.Customer Name});
Local NumberVar i;
For i := strLen To 1 Step -1 Do
(
   str := str + {Customer.Customer Name}[i]
);
str

Example 3

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

//Reverse a string version 3
StrReverse ({Customer.Customer Name})

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

See Also

For Loops Example | Exiting from For Loops