Crystal Reports  

While Loops (Crystal Syntax)

A While loop can be used to execute a fixed block of statement an indefinite amount of time.

Two Types of While Loops

Type of Loop Explanation Example
While ... Do The While ... Do loop evaluates the condition, and if the condition is true, then it evaluates the expression following the Do.

When it has finished doing this, it evaluates the condition again and if the condition is true, it evaluates the expression following the Do again.

It continues repeating this process until the condition is false.

While condition Do
   expression
Do ... While The Do ... While loop evaluates the expression once no matter what.

It then evaluates the condition, and if the condition is true, evaluates the expression again. This process continues until the condition is false.

Do
   expression
While condition
Note   The While loops support an Exit While statement to immediately jump out of the loop. Its use is analogous to the use of Exit For in For loops. As with the For loop, the While loop when considered as an expression always returns the Boolean value True.

While ... Do loop Example

The following example searches for the first occurrence of a digit in an input string. If a digit is found, it returns its position, otherwise it returns -1. In this case, the input string is set explicitly to a string constant, but it could be set equal to a String type database field instead.

For example, for the input String, "The 7 Dwarves", the formula returns 5, which is the position of the digit 7.

Local StringVar inString := "The 7 Dwarves";
Local NumberVar strLen := Length (inString);
Local NumberVar result := -1;
Local NumberVar i := 1;
While i <= strLen And result = -1 Do
(
   Local StringVar c := inString [i];
   If NumericText (c) Then
      result := i;
   i := i + 1;
);
result

See Also

Preventing Infinite Loops