RPGLE for loop example - AS400 (iSeries)

Instead of a dowhile or a dountil you can now use a for loop just any other language in RPGLE.
The syntax of the FOR operation is as follows:
      FOR         index-name { = starting-value }
                  { BY increment-value }
                  { TO | DOWNTO limit-value }
         { loop body }
      ENDFOR | END

The starting-value, increment-value, and limit-value can be numeric values or expressions with zero decimal positions. The increment value, if specified, cannot be zero. The BY and TO (or DOWNTO) clauses can be specified in either order. Both "BY 2 TO 99" and "TO 99 BY 2" are allowed.

Example 1:
for i=1 by 1 to 100;
     //do something
endfor;

Example 2:
Extract all blank-delimited words from a sentence.
    WordCnt = 0;
    for i = 1 by WordIncr to %len (Sentence);
       // Is there a blank?
       if %subst(Sentence: i: 1) = ' ';
          WordIncr = 1;
          iter;
       endif;
        // We've found a word - determine its length
       for j = i+1 to %len(Sentence);
          if %subst (Sentence: j: 1) = ' ';
             leave;
          endif;
       endfor;
        // Store the word
       WordIncr = j - i;
       WordCnt = WordCnt + 1;
       Word (WordCnt) = %subst (Sentence: i: WordIncr);
    endfor;

Source: IBM Information Center

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.