GNU Info

Info Node: (gawk.info)While Statement

(gawk.info)While Statement


Next: Do Statement Prev: If Statement Up: Statements
Enter node , (file) or (file)node

The `while' Statement
---------------------

   In programming, a "loop" is a part of a program that can be executed
two or more times in succession.  The `while' statement is the simplest
looping statement in `awk'.  It repeatedly executes a statement as long
as a condition is true.  For example:

     while (CONDITION)
       BODY

BODY is a statement called 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 the CONDITION.  If the
CONDITION is true, it executes the statement BODY.  (The CONDITION is
true when the value is not zero and not a null string.)  After BODY has
been executed, CONDITION is tested again, and if it is still true, BODY
is executed again.  This process repeats until the CONDITION is no
longer true.  If the CONDITION is initially false, the body of the loop
is never executed and `awk' continues with the statement following the
loop.  This example prints the first three fields of each record, one
per line:

     awk '{ i = 1
            while (i <= 3) {
                print $i
                i++
            }
     }' inventory-shipped

The body of this loop is a compound statement enclosed in braces,
containing two statements.  The loop works in the following manner:
first, the value of `i' is set to one.  Then, the `while' statement
tests whether `i' is less than or equal to three.  This is true when
`i' equals one, so the `i'-th field is printed.  Then the `i++'
increments the value of `i' and the loop repeats.  The loop terminates
when `i' reaches four.

   A newline is not required between the condition and the body;
however using one makes the program clearer unless the body is a
compound statement or else is very simple.  The newline after the
open-brace that begins the compound statement is not required either,
but the program is harder to read without it.


automatically generated by info2www version 1.2.2.9