while

  See Also

Related Topics

 

 

Description

The while statement gives a one or more instructions to be repeated a specified number of times.

 

 

Syntax

While condition do action

 

 

Parameters

condition

The condition controls the statement. Each passage through the statement, the condition is evaluated. When the condition is satisfied, the statement ends.

 

do

do is a convention of the while() statement. It introduces the action.

 

action

The action is the instruction to be repeated. To write multiple instructions, use a begin/end block.

 

 

Return Value

NA

 

 

Examples

fact4(n)=begin

result=1

while n>0 do begin

result=result*n

n=n-1

end

result

end

 

 

Comments

In the example, the calling formula passes a value to the argument n. fact4() then declares a variable result equal to 1. The while statement uses the begin/end keywords so that both of the lines within the begin/end block repeat “while” the value of n is greater than zero. The first line within the while statement sets the value of result equal to the product of the current value of result multiplied by the argument n. The second line within the while statement decrements the value of n by 1. Finally, the formula returns the value of result.

 

The following table summarizes how the return value of a call to fact4() with an argument of 5 is determined:

 

Value of n

Value of result

Calculation

Product

5

1

1x5

5

4

5

5x4

20

3

20

20x3

60

2

60

60x2

120

1

120

120x1

120

 

 

Return Value:

120