While

Top  Previous  Next

The While statement allows one to repeatedly execute a block of statements until a logical condition is satisfied.  Ordinarily, the syntax of the While statement is:

While (logical condition,

 statements to be executed While condition is true;

  );

But when $Onend is specified the statement becomes
$Onend
While conditional do
 statements ;
Endwhile;

Examples:

A binary root finder using While (While.gms) is as follows

 

While (converge = 0 and iter lt lim,

 root=(maxroot+minroot)/2;

 iter=iter+1;

 function_value=a-b*root+c*sqr(root);

 If(abs(function_value) lt tolerance,

         converge=1;

 else

                   If(sign(function_value1)=sign(function_value),

                  minroot=root;

                  function_value1=function_value;

         else

                  maxroot=root;

                  function_value2=function_value;

         );

  );

);

 

or

 

$onend

While converge = 0 and iter lt lim do

    root=(maxroot+minroot)/2;

    iter=iter+1;

    function_value=a-b*root+c*sqr(root);

    function_value=function_value;

    If(abs(function_value)) lt tolerance then

        converge=1;

    else

       if(sign(function_value1)=sign(function_value)) then

          minroot=root;

          function_value1=function_value;

       else

          maxroot=root;

          function_value2=function_value;

       endif;

    endif;

endwhile;

 

Notes:

When $onend is not present While is followed by an open ( and a close ) which surround the logical condition and the subsequent statements to be executed.  Furthermore the logical condition is followed by a comma.
When $onend is present While is followed by a logical condition possibly in parentheses then a do and the subsequent statements to be executed.  Finally the statement is ended with an Endwhile.
One cannot place parameter, acronym, set, file, table, model, equation, variable or scalar statements or .. equation declarations in the in the statements to be executed If condition is true.
Many other logical condition forms are possible as explained below.
The total number of passes through the While statements can be limited using the option Forlim.