Next: , Previous: The do-until Statement, Up: Statements


12.5 The for Statement

The for statement makes it more convenient to count iterations of a loop. The general form of the for statement looks like this:

     for var = expression
       body
     endfor

where body stands for any statement or list of statements, expression is any valid expression, and var may take several forms. Usually it is a simple variable name or an indexed variable. If the value of expression is a structure, var may also be a list. See Looping Over Structure Elements, below.

The assignment expression in the for statement works a bit differently than Octave's normal assignment statement. Instead of assigning the complete result of the expression, it assigns each column of the expression to var in turn. If expression is a range, a row vector, or a scalar, the value of var will be a scalar each time the loop body is executed. If var is a column vector or a matrix, var will be a column vector each time the loop body is executed.

The following example shows another way to create a vector containing the first ten elements of the Fibonacci sequence, this time using the for statement:

     fib = ones (1, 10);
     for i = 3:10
       fib (i) = fib (i-1) + fib (i-2);
     endfor

This code works by first evaluating the expression 3:10, to produce a range of values from 3 to 10 inclusive. Then the variable i is assigned the first element of the range and the body of the loop is executed once. When the end of the loop body is reached, the next value in the range is assigned to the variable i, and the loop body is executed again. This process continues until there are no more elements to assign.

Although it is possible to rewrite all for loops as while loops, the Octave language has both statements because often a for loop is both less work to type and more natural to think of. Counting the number of iterations is very common in loops and it can be easier to think of this counting as part of looping rather than as something to do inside the loop.