for

  See Also

Related Topics

 

 

Description

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

 

 

Syntax

for counter condition action

 

 

Parameters

counter

The counter must be a variable initialized to a number. Initialization occurs when the for() statement is entered. The counter is automatically incremented with each passage through the statement.

 

condition

The condition controls the statement. Each passage through the statement, the relationship between the counter and the condition is evaluated. When the condition is satisfied, the statement ends.

 

action

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

 

 

Return Value

NA

 

 

Examples

fact5(n)=begin

result=1

for i=1 to n result=result*i

result

end

 

 

Comments

The for statement is very similar to the while statement. In the example, the variable n is passed as an argument to the formula. A variable result is declared equal to 1. The for statement instructs the computer to set the value of result to the product of result multiplied by i. This calculation is repeated until i equals n.

 

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

 

Value of n

Value of result

Value of i

Calculation

Product

5

1

1

1x1

1

5

1

2

1x2

2

5

2

3

2x3

6

5

6

4

6x4

24

5

24

5

24x5

120

 

 

 

Return Value:

120