DADiSP Worksheet Functions > Function Categories > Control Flow > FOR

 

FOR

Purpose:

Performs FOR-Loop iterative statements.

Syntax:

FOR(expr1, expr2, expr3, statements)

FOR (expr1; expr2; expr3) { statements; }

expr1

-

An expression initializing the counter variable.

expr2

-

A conditional expression used to test the counter variable before each iteration. If non-zero, statement is evaluated.

expr3

-

An expression evaluated after each iteration of statement.

statements

-

Any valid expressions separated by semicolons. The statements to execute after each iteration.

Example:

for (j=1; j<=10; j++) echo(j);

 

sets j equal to 1 and increments j by 1 until j equals 10 while echoing j to the status line.

Example:

The SPL function, WinSines:

 

WinSines()
{
    local i, N;
 
    N = numwin;
 
    for (i = 1; i <= N; i++)
    {
        eval(sprintf("W%d := gsin(100,.01, %d)", i, i));
    }
}

 

increments local variable, i, and fills each Window in the Worksheet with a sinewave of the same frequency as the Window number. Note since i is declared as a local, it does not conflict with the built-in constant i == sqrt(-1).

Remarks:

The FOR function uses the same ; and , syntax as C/C++.

 

The expression:

 

for (expr1; expr2; expr3) statement;

 

is equivalent to:

 

expr1;
 
while (expr2)
{
    statement;
    expr3;
}

 

See LOOP for a faster, but less flexible iteration construct.

 

For best performance, try to avoid loops altogether by exploiting the vectorized nature of SPL. For example:

 

y = {};
t = 0..0.01..1;
 
for (n = 1; n <= 101; n++)
{
    y[n] = sin(2*pi*10*t[n]);
}

 

can be performed much faster, more intuitively and concisely with:

 

t = 0..0.01..1;
y = sin(2*pi*10*t);

 

or even faster with:

 

y = gsin(101, .01, 10);

See Also:

BREAK

CONTINUE

LOOP

RETURN

SPL: Series Processing Language

WHILE