Jump to content

Rexx Programming/How to Rexx/for loop

From Wikibooks, open books for an open world

"For" loops are also called "definite loops". They repeat the same block of code several times and stop. They are coded using the word "for" in many other languages, but in Rexx, they appear between the keywords DO and END, just like other blocks of code.

/* Greet the world 10 times: */
do 10
 say "Hello, world!"
end

If we want the code to do something slightly different each time it runs, we can use a variable to keep track of the counting.

/* Count from 1 to 10: */
do count = 1 to 10
 say count
end

Rexx can also skip count by 2s, 3s, 4s, or some other amount.

/* Count by 2s */
do count = 0 to 8 by 2
 say count
end

If you don't want to specify the last number but rather just how many times you'd like to count, then Rexx does actually have a FOR keyword that you can use.

/* Count out 5 numbers starting at -2 */
do count = -2 for 5
 say count
end

You can also nest definite loops inside each other for two or more levels of repetition.

/* Make a nicely formatted multiplication table. */
do row# = 1 to 10
 output = ""
 do col# = 1 to 10
  product = row# * col#
  output = output || right(product, 4)
 end
 say output
end