Skip to content

for

A syntactic looping construction.

Syntax

for var in array-expr do
... od

``` csound-orc
for var, index in array-expr do
... od

Performance

This expressions creates a loop controlled by an array expression or variable. In the first form, the loop iterates for each element in the array returned by array-expr, with the numeric value of the array setting the value of var at each iteration. The second form adds an index variable holding an index (0-based) used to access the array. This can be used as a loop count.The statements between the do and od form the body of a loop. Loop array expressions and variables are strictly of either i- or k-types.

The loop action time is determined by the following rules:

  • if var has been declared before the loop, the type (i or k) of this variable determines the action time (init or perf).

  • if var has not yet been declared, the array-expression type is used instead, and the variable is created to accept this type.

The index variable, if not declared, is created to match the type of _array-expr

Examples

Here is an example of the while construction. It uses the file forin.csd.

Example of the while opcode.
<CsoundSynthesizer>
<CsOptions>
-n
</CsOptions>
<CsInstruments>
0dbfs = 1

/* case 1
   loop var is not declared
   loop type follows array type
   (i-type in this case)
*/
instr 1
for j in [1,2,3] do
 print j
od
endin

/* case 2
   loop var is declared
   loop type follows var type
   regardless of array type
*/
instr 2
j:k init 0
for j in [1,2,3] do
 printk2 j
od
turnoff
endin

instr 3
for j, i in [2,4,6] do
 print i,j
od
turnoff
endin


</CsInstruments>
<CsScore>
i1 0 0
i2 0 1
i3 0 0
</CsScore>
</CsoundSynthesizer>

Its output should include lines like this:

instr 1:    j = 1.000
instr 1:    j = 2.000
instr 1:    j = 3.000
instr 3:    i = 0.000   j = 2.000
instr 3:    i = 1.000   j = 4.000
instr 3:    i = 2.000   j = 6.000
instr 2:        1.00000
instr 2:        2.00000
instr 2:        3.00000

See also

Program Flow Control: Looping Constructions

Credits

Hlodver Sigurdsson

New in Csound version 7