(octave.info)The while Statement


Next: The do-until Statement Prev: The switch Statement Up: Statements
Enter node , (file) or (file)node

10.3 The while Statement
========================

In programming, a “loop” means a part of a program that is (or at least
can be) executed two or more times in succession.

   The ‘while’ statement is the simplest looping statement in Octave.
It repeatedly executes a statement as long as a condition is true.  As
with the condition in an ‘if’ statement, the condition in a ‘while’
statement is considered true if its value is nonzero, and false if its
value is zero.  If the value of the conditional expression in a ‘while’
statement is a vector or a matrix, it is considered true only if it is
non-empty and _all_ of the elements are nonzero.

   Octave’s ‘while’ statement looks like this:

     while (CONDITION)
       BODY
     endwhile

Here BODY is a statement or list of statements that we call the “body”
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   The first thing the ‘while’ statement does is test CONDITION.  If
CONDITION is true, it executes the statement BODY.  After BODY has been
executed, CONDITION is tested again, and if it is still true, BODY is
executed again.  This process repeats until CONDITION is no longer true.
If CONDITION is initially false, the body of the loop is never executed.

   This example creates a variable ‘fib’ that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 3;
     while (i <= 10)
       fib (i) = fib (i-1) + fib (i-2);
       i++;
     endwhile

Here the body of the loop contains two statements.

   The loop works like this: first, the value of ‘i’ is set to 3.  Then,
the ‘while’ tests whether ‘i’ is less than or equal to 10.  This is the
case when ‘i’ equals 3, so the value of the ‘i’-th element of ‘fib’ is
set to the sum of the previous two values in the sequence.  Then the
‘i++’ increments the value of ‘i’ and the loop repeats.  The loop
terminates when ‘i’ reaches 11.

   A newline is not required between the condition and the body; but
using one makes the program clearer unless the body is very simple.


automatically generated by info2www version 1.2.2.9